#!/bin/bash
set -Eeuo pipefail
umask 027
bundle="$(realpath "${1:?Paquet attendu}")"; app=/srv/filyx/apps/web
[[ $EUID -eq 0 && "$bundle" == /tmp/filyx-giveaway-unified.* ]]
exec 9>/var/lock/filyx-giveaway-unified-deploy.lock; flock -n 9
cd "$app"; sha256sum --strict -c "$bundle/baseline.sha256"
files=(app/Services/GiveawayEntriesOverlayService.php app/Services/GiveawaySelectionService.php public/assets/css/giveaway-entries.css public/assets/js/giveaway-entries.js public/assets/js/giveaway-selection.js templates/overlay-giveaway-entries.php templates/overlay-giveaway-draw.php templates/dashboard.php routes/overlay.php routes/api.php)
for f in "${files[@]}"; do case "$f" in *.php) php -l "$bundle/stage/apps/web/$f" ;; esac; done
backup="/var/backups/filyx/giveaway-unified-$(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
php "$bundle/db.php" snapshot "$backup"
swap(){ local t; t="$(mktemp -- "$2.unified.XXXXXX")"; install -o root -g root -m 0644 -- "$1" "$t"; mv -f -- "$t" "$2"; }
rollback(){ local rc=$?; trap - ERR; for f in "${files[@]}"; do swap "$backup/$f" "$app/$f"; done; echo "Code restauré. Sauvegarde : $backup. Aucun point ni aucune participation effacée." >&2; exit "$rc"; }
trap rollback ERR
swap "$bundle/stage/apps/web/app/Services/GiveawayEntriesOverlayService.php" "$app/app/Services/GiveawayEntriesOverlayService.php"
# Let the existing two-second FPM revalidation window see the compatible helper first.
sleep 3
for f in "${files[@]:1}"; do swap "$bundle/stage/apps/web/$f" "$app/$f"; done
php "$bundle/verify.php" ready
systemctl is-active --quiet filyx-bot-engine.service; systemctl is-active --quiet filyx-twitch-engine.service
php "$bundle/db.php" activate "$backup"
trap - ERR
php "$bundle/db.php" verify "$backup"
php "$bundle/verify.php"
printf 'Déploiement global terminé. Sauvegarde : %s. Aucun changelog, tirage, message de test ni débit réel.\n' "$backup"
