#!/bin/bash
set -Eeuo pipefail
umask 027
bundle="$(realpath "${1:?Paquet attendu}")"
app=/srv/filyx/apps/web
[[ $EUID -eq 0 && "$bundle" == /tmp/filyx-giveaway-options.* ]]
exec 9>/var/lock/filyx-giveaway-options-deploy.lock
flock -n 9
cd "$app"
sha256sum --strict -c "$bundle/baseline.sha256"
existing=(routes/api.php templates/dashboard.php app/Services/GiveawaySelectionService.php public/assets/js/giveaway-selection.js routes/api-giveaway-selection.php public/assets/previews/gtavi-lenzo-test-20261118/index.html public/assets/previews/gtavi-lenzo-test-20261118/simulation.js)
added=(app/Services/GiveawayEntryService.php)
[[ ! -e "$app/${added[0]}" ]]
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
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/giveaways)" == 302 ]]
backup="/var/backups/filyx/giveaway-options-$(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
php "$bundle/migrate.php" "$backup"
swap() {
  local tmp
  tmp="$(mktemp -- "$2.giveaway-options.XXXXXX")"
  install -o root -g root -m 0644 -- "$1" "$tmp"
  mv -f -- "$tmp" "$2"
}
rollback() {
  local rc=$?
  trap - ERR
  set +e
  for f in "${existing[@]}"; do swap "$backup/$f" "$app/$f"; done
  echo "Code restauré ; ajouts de schéma conservés, aucun solde modifié." >&2
  exit "$rc"
}
trap rollback ERR
# Install services before routes/UI. The database additions are backward compatible.
for f in "${added[@]}" app/Services/GiveawaySelectionService.php routes/api-giveaway-selection.php routes/api.php public/assets/js/giveaway-selection.js templates/dashboard.php public/assets/previews/gtavi-lenzo-test-20261118/simulation.js public/assets/previews/gtavi-lenzo-test-20261118/index.html; do
  swap "$bundle/stage/apps/web/$f" "$app/$f"
done
[[ "$(probe /login)" == 200 && "$(probe /panel/giveaways)" == 302 && "$(probe /api/giveaways/7/entries)" == 401 ]]
[[ "$(probe /assets/js/giveaway-selection.js?v=20261118-points-messages)" == 200 ]]
[[ "$(probe /assets/previews/gtavi-lenzo-test-20261118/index.html)" == 200 ]]
curl -fsS --max-time 8 --resolve filyx.fr:443:127.0.0.1 'https://filyx.fr/assets/js/giveaway-selection.js?v=20261118-points-messages' -o "$backup/published-script.js"
grep -q 'entry_points_cost:Number(cost.value)' "$backup/published-script.js"
if grep -qi 'lenzo' "$app/public/assets/previews/gtavi-lenzo-test-20261118/index.html" "$app/public/assets/previews/gtavi-lenzo-test-20261118/simulation.js"; then false; fi
trap - ERR
printf 'Options giveaway publiées sans tirage ni message. Sauvegarde : %s\n' "$backup"
