#!/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"
DATA_DIR="${NIVATO_DATA_DIR:-/opt/nivato-logger/data}"
READY_MARKER="$DATA_DIR/update-ready-version"

# shellcheck source=/dev/null
. /opt/nivato-logger/bin/apt-ensure-keyring
nivato_ensure_apt_keyring_and_sources || true

/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
