#!/bin/bash
# Sprawdza, czy w repo jest nowsza wersja nivato-logger.
# Wyjście (stdout): INSTALLED=… / CANDIDATE=… / AVAILABLE=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"

# Upewnij się, że suite jest bookworm (stare instalacje).
if [ -f "$SOURCES" ] && grep -q '^Suites:.*nivato-logger' "$SOURCES" 2>/dev/null; then
    cat > "$SOURCES" <<'EOF'
Types: deb
URIs: https://apt.nivato.app/
Suites: bookworm
Components: main
Architectures: arm64
Trusted: yes
EOF
    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

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