#!/bin/bash
set -Eeuo pipefail
umask 027
bundle="$(realpath "${1:?Paquet attendu}")"
app=/srv/filyx/apps/web
[[ $EUID -eq 0 && "$bundle" == /tmp/filyx-giveaway-tickets.* ]]
exec 9>/var/lock/filyx-giveaway-tickets-deploy.lock
flock -n 9
cd "$app"
sha256sum --strict -c "$bundle/baseline.sha256"
while IFS= read -r f; do php -l "$f"; done < <(find "$bundle/stage/apps/web" -type f -name '*.php')
backup="/var/backups/filyx/giveaway-tickets-$(date -u +%Y%m%d-%H%M%S)"
install -d -m 0700 "$backup"
files=(app/Services/GiveawayEntryService.php app/Services/GiveawaySelectionService.php app/Services/GiveawayEntriesOverlayService.php routes/api.php routes/api-giveaway-selection.php templates/dashboard.php templates/overlay-giveaway-entries.php public/assets/js/app.js public/assets/js/giveaway-selection.js public/assets/js/giveaway-entries.js public/assets/css/giveaway-entries.css)
for f in "${files[@]}"; do install -d -m 0700 "$backup/$(dirname "$f")"; cp -a -- "$app/$f" "$backup/$f"; done
cp -- "$bundle/migration.sql" "$backup/migration.sql"
php "$bundle/db.php" snapshot "$backup"
php "$bundle/db.php" migrate "$backup"
swap(){ local t; t="$(mktemp -- "$2.tickets.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 précédent restauré ; schéma additif conservé. Aucune participation ni aucun solde restauré/effacé. Sauvegarde : $backup" >&2; exit "$rc"; }
trap rollback ERR
for f in "${files[@]}"; do swap "$bundle/stage/apps/web/$f" "$app/$f"; done
php "$bundle/verify.php"
systemctl is-active --quiet filyx-bot-engine.service
systemctl is-active --quiet filyx-twitch-engine.service
# Enable the new behavior only after the source and the application are healthy.
php "$bundle/db.php" activate "$backup"
trap - ERR
php "$bundle/db.php" verify "$backup"
php "$bundle/verify.php"
printf 'Correctif publié. Sauvegarde : %s. Aucun changelog ni message de test envoyé.\n' "$backup"
