#!/usr/bin/env bash
set -euo pipefail

# --- Réglages ---
LOGFILE="/var/log/auto-upgrade.log"
LOCKFILE="/var/run/auto-upgrade.lock"
export DEBIAN_FRONTEND=noninteractive
APT_OPTS=(-y -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold)

# --- Vérification root ---
if [ "$(id -u)" -ne 0 ]; then
  echo "Ce script doit être exécuté en root." >&2
  exit 1
fi

# --- Logging ---
umask 022
mkdir -p "$(dirname "$LOGFILE")"
if [ -t 1 ]; then
  exec > >(tee -a "$LOGFILE") 2>&1
else
  exec >>"$LOGFILE" 2>&1
fi

echo "===== $(date -Is) : démarrage auto-upgrade (Debian/Ubuntu) ====="

# --- Lock pour éviter les collisions ---
exec 9>"$LOCKFILE"
if ! flock -n 9; then
  echo "Un autre auto-upgrade est déjà en cours, arrêt."
  exit 0
fi

# --- Update & upgrade ---
echo "[1/4] apt-get update"
apt-get update

echo "[2/4] apt-get upgrade"
apt-get upgrade "${APT_OPTS[@]}"

# --- Full-upgrade/disto si besoin ---
echo "[3/4] Vérification si un full-upgrade est nécessaire…"
if apt-get -s dist-upgrade | awk '/^Inst / { found=1; exit } END { exit !found }'; then
  echo "Des paquets nécessitent un full-upgrade → exécution."
  apt-get dist-upgrade "${APT_OPTS[@]}"
else
  echo "Full-upgrade non nécessaire."
fi

# --- Autoremove ---
echo "[4/4] apt-get autoremove --purge"
apt-get autoremove --purge -y

# --- Reboot si requis ---
if [ -f /var/run/reboot-required ]; then
  PKG_COUNT=$(wc -l < /var/run/reboot-required.pkgs 2>/dev/null || echo 0)
  echo "Reboot nécessaire (${PKG_COUNT} paquet(s) impliqué(s))."
  /sbin/reboot
else
  echo "Pas besoin de reboot."
fi

echo "===== $(date -Is) : fin auto-upgrade ====="
echo "--------------------------------------------------------"
exit 0