#!/bin/sh
set -e

OBS_BASE="https://download.opensuse.org/repositories/home:/nicoletta:/myapps"
REPO_FILE="/etc/apt/sources.list.d/myapps-obs.list"
KEY_FILE="/etc/apt/trusted.gpg.d/myapps-obs.gpg"

# OBS-Repo automatisch eintragen (nur beim ersten Install)
if [ ! -f "$REPO_FILE" ]; then
    # Distro erkennen
    if [ -f /etc/os-release ]; then
        . /etc/os-release
    fi

    DIST=""
    case "$ID" in
        debian)
            case "$VERSION_CODENAME" in
                bookworm) DIST="Debian_12" ;;
                trixie)   DIST="Debian_13" ;;
                *)        DIST="Debian_12" ;;
            esac
            ;;
        ubuntu)
            case "$VERSION_ID" in
                "22.04") DIST="xUbuntu_22.04" ;;
                "24.04") DIST="xUbuntu_24.04" ;;
                "25.10") DIST="xUbuntu_25.10" ;;
                "26.04") DIST="xUbuntu_26.04" ;;
                *)       DIST="xUbuntu_24.04" ;;
            esac
            ;;
        linuxmint)
            case "$UBUNTU_CODENAME" in
                jammy) DIST="xUbuntu_22.04" ;;
                noble) DIST="xUbuntu_24.04" ;;
                *)     DIST="xUbuntu_24.04" ;;
            esac
            ;;
    esac

    if [ -n "$DIST" ]; then
        REPO_URL="${OBS_BASE}/${DIST}/"

        # Repo-Datei eintragen
        echo "deb ${REPO_URL} /" > "$REPO_FILE"

        # GPG-Key herunterladen (wget, curl oder python3)
        KEY_URL="${REPO_URL}Release.key"
        if command -v wget >/dev/null 2>&1; then
            wget -qO- "$KEY_URL" | gpg --dearmor > "$KEY_FILE" 2>/dev/null || rm -f "$KEY_FILE"
        elif command -v curl >/dev/null 2>&1; then
            curl -fsSL "$KEY_URL" | gpg --dearmor > "$KEY_FILE" 2>/dev/null || rm -f "$KEY_FILE"
        else
            python3 -c "
import urllib.request, subprocess, sys
try:
    key = urllib.request.urlopen('$KEY_URL', timeout=10).read()
    p = subprocess.run(['gpg','--dearmor'], input=key, capture_output=True)
    open('$KEY_FILE','wb').write(p.stdout)
except Exception as e:
    sys.exit(0)
" 2>/dev/null || true
        fi
    fi
fi

# Icon-Cache + Desktop-Datenbank aktualisieren
if command -v gtk-update-icon-cache >/dev/null 2>&1; then
    gtk-update-icon-cache -f -t /usr/share/icons/hicolor 2>/dev/null || true
fi
if command -v update-desktop-database >/dev/null 2>&1; then
    update-desktop-database -q /usr/share/applications 2>/dev/null || true
fi
