#!/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:
#   - Refresh our source for panel upgrades; the PHP security helper also
#     refreshes configured APT sources to discover vendor PHP fixes.
#   - Upgrade our packages and installed PHP packages (PHP2Shell fixes).
#     Never request upgrades of unrelated packages.
#   - 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

# A panel repository failure must not prevent the independent PHP retry.
# Keep the overall failure visible even if PHP remediation succeeds.
failed=0
{
  echo "==== ${STAMP} updater start (packages:${PKGS}) ===="
  if [ -e /etc/apt/sources.list.d/maxpanel.sources ]; then
    # Refresh only the panel source here; the PHP helper refreshes all
    # configured sources independently. Keep unrelated cached lists.
    # Installed package names are deliberately split into arguments.
    # shellcheck disable=SC2086
    if apt-get \
        -o Dir::Etc::sourceparts="-" \
        -o Dir::Etc::sourcelist="sources.list.d/maxpanel.sources" \
        -o APT::Get::List-Cleanup="0" \
        update &&
        DEBIAN_FRONTEND=noninteractive apt-get install -y --only-upgrade $PKGS; then
      echo "MaxPanel package update completed"
    else
      echo "MaxPanel package update failed; continuing PHP security remediation"
      failed=1
    fi
  else
    echo "${STAMP} /etc/apt/sources.list.d/maxpanel.sources missing — cannot self-update; continuing PHP security remediation"
    failed=1
  fi
  if ! /usr/local/sbin/maxpanel-php-security --upgrade; then
    echo "PHP security remediation failed; retry required"
    failed=1
  fi
  echo "==== $(date -u +%Y-%m-%dT%H:%M:%SZ) done (failure=${failed}) ===="
} >> "$LOG" 2>&1
exit "$failed"
