#!/bin/sh
# maxpanel-updater.sh — pull the latest maxpanel* packages from our APT
# repo and install them. Invoked daily by maxpanel-updater.timer.
#
# Design goals:
#   - Only refresh OUR APT source, never touch the operator's other
#     sources or the system-wide apt cache.
#   - Only upgrade OUR packages (auto-detected via dpkg). Cannot
#     accidentally install a new package or upgrade unrelated stuff.
#   - Idempotent, quiet on the happy path, verbose on failure — all
#     output tees into /var/log/maxpanel/updater.log for postmortem.
#   - Opt-out: touch /etc/maxpanel/no-autoupdate to disable. Sentinel
#     is not owned by the .deb (survives reinstalls and upgrades).
#
# The systemd timer that drives this uses RandomizedDelaySec=6h so a
# fleet of customer panels never hammers apt.maxpanel.net at the same
# second. Persistent=true means boxes that were off catch up on boot.

set -eu

LOG_DIR=/var/log/maxpanel
LOG="${LOG_DIR}/updater.log"
SENTINEL=/etc/maxpanel/no-autoupdate
STAMP="$(date -u +%Y-%m-%dT%H:%M:%SZ)"

mkdir -p "$LOG_DIR" 2>/dev/null || true

if [ -e "$SENTINEL" ]; then
  echo "${STAMP} disabled (${SENTINEL} present) — skipping" >> "$LOG"
  exit 0
fi

# Enumerate which of our packages are installed. Empty result → we're
# on a host that has systemd + timer but no maxpanel binary (rare, but
# shouldn't crash).
PKGS=""
for p in maxpanel maxpanel-mail; do
  if dpkg -s "$p" >/dev/null 2>&1; then
    PKGS="${PKGS} $p"
  fi
done
if [ -z "$PKGS" ]; then
  echo "${STAMP} no maxpanel packages installed — nothing to do" >> "$LOG"
  exit 0
fi

# The maxpanel APT source is /etc/apt/sources.list.d/maxpanel.sources
# (deb822 format, laid down by install.sh). Bail out clearly if it
# vanished — that's an operator-visible misconfiguration, not something
# we should silently retry against forever.
if [ ! -e /etc/apt/sources.list.d/maxpanel.sources ]; then
  echo "${STAMP} /etc/apt/sources.list.d/maxpanel.sources missing — cannot self-update" >> "$LOG"
  exit 1
fi

{
  echo "==== ${STAMP} updater start (packages:${PKGS}) ===="
  # Refresh ONLY our source. `-o Dir::Etc::sourceparts=-` empties the
  # per-file source directory scan, then sourcelist adds ours back.
  # List-Cleanup=0 stops apt from pruning caches from unrelated sources.
  apt-get \
    -o Dir::Etc::sourceparts="-" \
    -o Dir::Etc::sourcelist="sources.list.d/maxpanel.sources" \
    -o APT::Get::List-Cleanup="0" \
    update
  # --only-upgrade guarantees we never install a new package (belt +
  # braces vs the dpkg -s check above).
  DEBIAN_FRONTEND=noninteractive apt-get install -y --only-upgrade $PKGS
  echo "==== $(date -u +%Y-%m-%dT%H:%M:%SZ) done ===="
} >> "$LOG" 2>&1
