#!/bin/bash
set -Eeuo pipefail
umask 027
bundle="$(realpath "${1:?Dossier de déploiement attendu}")"
app=/srv/filyx/apps/web
[[ $EUID -eq 0 && "$bundle" == /tmp/filyx-giveaway-auto.* ]]
exec 9>/var/lock/filyx-giveaway-auto-entry-deploy.lock
flock -n 9
cd "$app"
sha256sum --strict -c "$bundle/baseline.sha256"
files=(app/Services/GiveawayEntryService.php routes/api.php public/assets/js/giveaway-selection.js templates/dashboard.php)
for f in "${files[@]}"; 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-auto-entry-$(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 temp
  temp="$(mktemp -- "$2.giveaway-auto.XXXXXX")"
  install -o root -g root -m 0644 -- "$1" "$temp"
  mv -f -- "$temp" "$2"
}
rollback() {
  local rc=$?
  trap - ERR
  for f in "${files[@]}"; do swap "$backup/$f" "$app/$f"; done
  echo "Code précédent restauré ; aucun réglage ni solde modifié par ce déploiement." >&2
  exit "$rc"
}
trap rollback ERR
for f in "${files[@]}"; do
  swap "$bundle/stage/apps/web/$f" "$app/$f"
  [[ "$(sha256sum "$app/$f" | cut -d' ' -f1)" == "$(sha256sum "$bundle/stage/apps/web/$f" | cut -d' ' -f1)" ]]
done
[[ "$(probe /login)" == 200 && "$(probe /panel/giveaways)" == 302 && "$(probe /api/giveaways/9/entries)" == 401 ]]
curl -fsS --max-time 8 --resolve filyx.fr:443:127.0.0.1 'https://filyx.fr/assets/js/giveaway-selection.js?v=20261118-auto-entry' -o "$backup/published-script.js"
grep -q 'sans code ni deuxième message' "$backup/published-script.js"
! grep -q 'confirmation_required' "$app/routes/api.php"
! grep -q 'confirmation_required\|confirmationMessage' "$app/app/Services/GiveawayEntryService.php"
trap - ERR
printf 'Inscription automatique publiée, sans reprise ni débit des anciennes attentes. Aucun tirage ni message de test. Sauvegarde : %s\n' "$backup"
