#!/bin/bash
set -Eeuo pipefail
umask 027
bundle="$(realpath "${1:?Dossier attendu}")"
app=/srv/filyx/apps/web
[[ $EUID -eq 0 && "$bundle" == /tmp/filyx-giveaway-entries.* ]]
exec 9>/var/lock/filyx-giveaway-entries-deploy.lock
flock -n 9
cd "$app"
sha256sum --strict -c "$bundle/baseline.sha256"
existing=(routes/api.php routes/overlay.php templates/dashboard.php)
added=(app/Services/GiveawayEntriesOverlayService.php templates/overlay-giveaway-entries.php public/assets/css/giveaway-entries.css public/assets/css/giveaway-entries-panel.css public/assets/js/giveaway-entries.js)
for f in "${added[@]}"; do if [[ -e "$app/$f" ]]; then cmp -s "$app/$f" "$bundle/stage/apps/web/$f"; fi; done
for f in "${existing[@]}" "${added[@]}"; do
  [[ -f "$bundle/stage/apps/web/$f" ]]
  case "$f" in *.php) php -l "$bundle/stage/apps/web/$f" >/dev/null ;; *.js) node --check "$bundle/stage/apps/web/$f" ;; esac
done
php "$bundle/preflight.php"
backup="/var/backups/filyx/giveaway-entries-$(date -u +%Y%m%d-%H%M%S)"
install -d -m 0700 "$backup"
for f in "${existing[@]}"; do install -d -m 0700 "$backup/$(dirname "$f")"; cp -a -- "$app/$f" "$backup/$f"; done
swap(){ local t; t="$(mktemp -- "$2.entries.XXXXXX")"; install -o root -g root -m 0644 -- "$1" "$t"; mv -f -- "$t" "$2"; }
rollback(){ local rc=$?; trap - ERR; for f in "${existing[@]}"; do swap "$backup/$f" "$app/$f"; done; echo 'Routes précédentes restaurées ; aucune donnée modifiée.' >&2; exit "$rc"; }
trap rollback ERR
for f in "${added[@]}" "${existing[@]}"; do swap "$bundle/stage/apps/web/$f" "$app/$f"; done
php "$bundle/verify.php"
[[ "$(curl -sS --max-time 8 --resolve filyx.fr:443:127.0.0.1 -o /dev/null -w '%{http_code}' https://filyx.fr/login)" == 200 ]]
trap - ERR
printf 'Overlay des inscrits publié. Aucun compte, réglage, point, tirage, message ou changelog modifié. Sauvegarde : %s\n' "$backup"
