#!/bin/sh
# =========================================================================
# khos-installer-update - Pobieranie i aktualizacja instalatora KhOS z serwera pakietów
# Pobiera najnowszą wersję instalatora z https://git.kpgpmc.org/KhOS/KhOS-packages
# =========================================================================
set -e
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH"

C_RESET='\033[0m'
C_BOLD='\033[1m'
C_RED='\033[1;31m'
C_GREEN='\033[1;32m'
C_YELLOW='\033[1;33m'
C_CYAN='\033[1;36m'
C_BLUE='\033[1;34m'

msg()  { printf "${C_BOLD}${C_BLUE}==>${C_RESET} ${C_BOLD}%s${C_RESET}\n" "$1"; }
info() { printf "${C_CYAN} ->${C_RESET} %s\n" "$1"; }
ok()   { printf "${C_GREEN} [OK]${C_RESET} %s\n" "$1"; }
warn() { printf "${C_YELLOW}[OSTRZEŻENIE]${C_RESET} %s\n" "$1"; }
err()  { printf "${C_RED}[BŁĄD]${C_RESET} %s\n" "$1" >&2; }

echo "══════════════════════════════════════════════════════════════"
echo "  KhOS Linux - Aktualizacja instalatora z serwera pakietów    "
echo "══════════════════════════════════════════════════════════════"

# 1. Sprawdzenie uprawnień administratora
if [ "$(id -u 2>/dev/null)" != "0" ]; then
    err "Ten program wymaga uprawnień administratora root. Uruchom polecenie z 'sudo'."
    exit 1
fi

REPO_BASE="https://git.kpgpmc.org/KhOS/KhOS-packages/raw/branch/main"
CA_OPT=""
[ -f /etc/ssl/certs/ca-certificates.crt ] && CA_OPT="--cacert /etc/ssl/certs/ca-certificates.crt"

# 2. Sprawdzenie połączenia sieciowego
info "Sprawdzanie połączenia z serwerem pakietów git.kpgpmc.org..."
NET_OK=0
if command -v curl >/dev/null 2>&1; then
    if curl -fsSL -I --connect-timeout 5 $CA_OPT "https://git.kpgpmc.org" >/dev/null 2>&1; then
        NET_OK=1
    fi
elif command -v wget >/dev/null 2>&1; then
    if wget -q --spider --timeout=5 "https://git.kpgpmc.org" 2>/dev/null; then
        NET_OK=1
    fi
fi

if [ "$NET_OK" -ne 1 ]; then
    err "Brak połączenia z serwerem pakietów git.kpgpmc.org!"
    warn "Upewnij się, że kabel sieciowy jest podłączony lub skonfiguruj WiFi/DHCP (polecenie: udhcpc)."
    exit 1
fi
ok "Połączenie z serwerem pakietów jest aktywne."

# 3. Metoda 1: Użycie menedżera pakietów wpkg (jeśli dostępny)
if command -v wpkg >/dev/null 2>&1; then
    info "Aktualizacja bazy pakietów z repozytorium..."
    if wpkg update; then
        info "Pobieranie i instalowanie najnowszego pakietu khos-installer..."
        if wpkg install --force khos-installer 2>/dev/null || wpkg install khos-installer; then
            ok "Instalator KhOS został pomyślnie zaktualizowany przez menedżer wpkg!"
            chmod +x /usr/bin/khos-installer /usr/bin/khos-installer-gui /usr/share/khos-installer/*.py 2>/dev/null || true
            exit 0
        fi
    fi
fi

# 4. Metoda 2: Bezpośrednie pobranie najnowszego archiwum .wpkg z serwera
info "Pobieranie najnowszego pakietu instalatora bezpośrednio z serwera Git..."
TMP_DIR="/tmp/khos-installer-update-$$"
mkdir -p "$TMP_DIR"
PKG_FILE="$TMP_DIR/khos-installer.wpkg"

DOWNLOAD_URL="${REPO_BASE}/packages/khos-installer-1.1.0-1-x86_64.wpkg"
if command -v curl >/dev/null 2>&1; then
    curl -fsSL $CA_OPT -o "$PKG_FILE" "$DOWNLOAD_URL" || true
elif command -v wget >/dev/null 2>&1; then
    wget -q -O "$PKG_FILE" "$DOWNLOAD_URL" || true
fi

if [ ! -s "$PKG_FILE" ]; then
    err "Nie udało się pobrać pliku pakietu z $DOWNLOAD_URL!"
    rm -rf "$TMP_DIR"
    exit 1
fi

info "Rozpakowywanie i instalowanie zaktualizowanego instalatora..."
tar -xzf "$PKG_FILE" -C "$TMP_DIR" 2>/dev/null || tar -xf "$PKG_FILE" -C "$TMP_DIR" 2>/dev/null || true

if [ -d "$TMP_DIR/data" ]; then
    cp -a "$TMP_DIR/data/"* / 2>/dev/null || true
fi

# Ustawienie uprawnień wykonywania
chmod +x /usr/bin/khos-installer /usr/bin/khos-installer-gui /usr/bin/install-os /usr/share/khos-installer/*.py 2>/dev/null || true
rm -rf "$TMP_DIR"

ok "Pomyślnie zainstalowano najnowszą wersję instalatora KhOS z serwera git.kpgpmc.org!"
info "Możesz teraz uruchomić instalator wpisując: khos-installer lub khos-installer-gui"
