#!/bin/bash
set -Eeuo pipefail
umask 027
bundle="$(realpath "${1:?Paquet Studio attendu}")"
app=/srv/filyx/apps/web
[[ $EUID -eq 0 && "$bundle" == /tmp/filyx-studio-alerts.* && -f "$app/config/overlay-studio.public" ]]
exec 9>/var/lock/filyx-studio-deploy.lock
flock -n 9
cd "$app"
sha256sum --strict -c "$bundle/alerts-20261117/baseline.txt"
mapfile -t files < <(awk '{print $2}' "$bundle/alerts-20261117/baseline.txt")
frame=templates/overlay-studio-alert-frame.php
[[ ! -e "$app/$frame" ]]
for f in "${files[@]}" "$frame"; do
  [[ -f "$bundle/stage/apps/web/$f" ]]
  case "$f" in
    *.php) php -l "$bundle/stage/apps/web/$f" >/dev/null ;;
    *.js) node --input-type=module --check < "$bundle/stage/apps/web/$f" ;;
  esac
done
probe() { curl -sS --connect-timeout 4 --max-time 8 --resolve filyx.fr:443:127.0.0.1 -o /dev/null -w '%{http_code}' "https://filyx.fr$1"; }
[[ "$(probe /login)" == 200 && "$(probe /panel/overlays)" == 302 ]]
backup="/var/backups/filyx/overlay-studio-alerts-$(date -u +%Y%m%d-%H%M%S)"
install -d -m 0700 "$backup"
for f in "${files[@]}"; do
  install -d -m 0700 "$backup/$(dirname "$f")"
  cp -a -- "$app/$f" "$backup/$f"
done
swap() {
  local tmp
  tmp="$(mktemp -- "$2.studio.XXXXXX")"
  install -o root -g root -m 0644 -- "$1" "$tmp"
  mv -f -- "$tmp" "$2"
}
rollback() {
  local rc=$?
  trap - ERR
  set +e
  for f in "${files[@]}"; do swap "$backup/$f" "$app/$f"; done
  if [[ -f "$app/$frame" ]]; then mv -- "$app/$frame" "$backup/alert-frame.disabled.php"; fi
  echo "Restauration du Studio après échec de contrôle." >&2
  exit "$rc"
}
trap rollback ERR
# Versions before the template (asset cache key) and supporting route.
swap "$bundle/stage/apps/web/$frame" "$app/$frame"
for f in "${files[@]}"; do
  case "$f" in
    routes/overlay-studio.php|templates/overlay-studio.php) ;;
    *) swap "$bundle/stage/apps/web/$f" "$app/$f" ;;
  esac
done
php "$bundle/import-20261117/probe.php"
for f in routes/overlay-studio.php templates/overlay-studio.php; do
  swap "$bundle/stage/apps/web/$f" "$app/$f"
done
# The preflight panel check may have warmed the old PHP route in OPcache.
for ignored in {1..12}; do
  frame_status="$(probe /api/overlay-studio/alert-frame)"
  [[ "$frame_status" == 200 ]] && break
  sleep 1
done
[[ "$frame_status" == 200 ]] || { printf 'Route du cadre : HTTP %s\n' "$frame_status" >&2; false; }
curl -fsS --max-time 8 --resolve filyx.fr:443:127.0.0.1 -D "$backup/frame.headers" -o "$backup/frame.html" 'https://filyx.fr/api/overlay-studio/alert-frame'
grep -qi "^content-security-policy: sandbox allow-scripts;" "$backup/frame.headers"
grep -q 'filyx-studio-alert' "$backup/frame.html"
[[ "$(probe /login)" == 200 && "$(probe /panel/overlays/import)" == 302 && "$(probe '/assets/js/overlay-studio-v2/render.js?v=20261117-alerts')" == 200 ]]
trap - ERR
printf 'Alertes personnalisées et glissements Studio déployés sans changement de base. Sauvegarde : %s\n' "$backup"
