#!/bin/bash
# Sprawdza, czy w repo jest nowsza wersja nivato-logger.
# Wyjście (stdout): INSTALLED=… / CANDIDATE=… / AVAILABLE=0|1 / DOWNLOADED=0|1
# Exit zawsze 0 przy udanym sprawdzeniu; 1 przy błędzie narzędzi.
set -euo pipefail

export DEBIAN_FRONTEND=noninteractive
PACKAGE="nivato-logger"
SOURCES="/etc/apt/sources.list.d/nivato-logger.sources"
KEYRING="/usr/share/keyrings/nivato-logger.gpg"
DATA_DIR="${NIVATO_DATA_DIR:-/opt/nivato-logger/data}"
READY_MARKER="$DATA_DIR/update-ready-version"

# Migruj tylko stary suite; nie nadpisuj Signed-By przez Trusted:yes.
if [ -f "$SOURCES" ] && grep -qE '^Suites:.*(nivato-logger|stable)' "$SOURCES" 2>/dev/null; then
    if [ -f "$KEYRING" ]; then
        cat > "$SOURCES" <<EOF
Types: deb
URIs: https://apt.nivato.app/
Suites: bookworm
Components: main
Architectures: arm64
Signed-By: $KEYRING
EOF
    else
        cat > "$SOURCES" <<'EOF'
Types: deb
URIs: https://apt.nivato.app/
Suites: bookworm
Components: main
Architectures: arm64
Trusted: yes
EOF
    fi
    chmod 644 "$SOURCES"
elif [ -f "$SOURCES" ] && [ -f "$KEYRING" ] && grep -q '^Trusted: yes' "$SOURCES" 2>/dev/null; then
    tmp=$(mktemp)
    sed '/^Trusted: yes/d' "$SOURCES" > "$tmp"
    if ! grep -q '^Signed-By:' "$tmp"; then
        printf 'Signed-By: %s\n' "$KEYRING" >> "$tmp"
    fi
    mv "$tmp" "$SOURCES"
    chmod 644 "$SOURCES"
fi

/usr/bin/apt-get update -o Acquire::Retries=2 -qq 2>/dev/null || true

installed="$(dpkg-query -W -f='${Version}' "$PACKAGE" 2>/dev/null || true)"
candidate="$(apt-cache policy "$PACKAGE" 2>/dev/null | awk '/Candidate:/ { print $2; exit }')"

available=0
if [ -n "$candidate" ] && [ "$candidate" != "(none)" ]; then
    if [ -z "$installed" ] || dpkg --compare-versions "$installed" lt "$candidate"; then
        available=1
    fi
fi

downloaded=0
if [ "$available" = "1" ] && [ -n "$candidate" ]; then
    if compgen -G "/var/cache/apt/archives/${PACKAGE}_${candidate}_*.deb" > /dev/null 2>&1; then
        downloaded=1
    elif [ -f "$READY_MARKER" ] && [ "$(tr -d '[:space:]' < "$READY_MARKER")" = "$candidate" ]; then
        downloaded=1
    fi
fi

printf 'INSTALLED=%s\n' "${installed:-}"
printf 'CANDIDATE=%s\n' "${candidate:-}"
printf 'AVAILABLE=%s\n' "$available"
printf 'DOWNLOADED=%s\n' "$downloaded"
exit 0
