#!/bin/bash
set -Eeuo pipefail
umask 027
bundle="$(realpath "${1:?Dossier test attendu}")"
[[ $EUID -eq 0 && "$bundle" == /tmp/filyx-giveaway-test.* ]]
app=/srv/filyx/apps/web
parent="$app/public/assets/previews"
target="$parent/gtavi-lenzo-test-20261118"
exec 9>/var/lock/filyx-giveaway-public-preview.lock
flock -n 9
[[ ! -e "$target" ]]
cd "$bundle/public"
sha256sum --strict -c ../manifest.sha256
[[ $(find . -mindepth 1 -maxdepth 1 -type f | wc -l) -eq 2 ]]
node --check simulation.js
if grep -Eiq '/api/|XMLHttpRequest|WebSocket|EventSource|fetch[[:space:]]*\(' index.html simulation.js; then echo 'Accès au moteur refusé.' >&2; exit 1; fi
grep -q 'SIMULATION PUBLIQUE' index.html
grep -q 'RÉSULTAT SIMULÉ' simulation.js
[[ "$(curl -sS --max-time 8 --resolve filyx.fr:443:127.0.0.1 -o /dev/null -w '%{http_code}' https://filyx.fr/login)" == 200 ]]
# A presentation-only, data-free test page; no live route or database update.
before="$(php "$bundle/presentation.php" | sha256sum | cut -d ' ' -f 1)"
install -d -m 0755 "$parent"
newdir="$(mktemp -d "$parent/.gtavi-preview.XXXXXXXX")"
install -m 0644 -o root -g root index.html simulation.js "$newdir/"
chmod 0755 "$newdir"
mv -T -- "$newdir" "$target"
rollback() {
  local rc=$?
  trap - ERR
  if [[ -d "$target" ]]; then mv -- "$target" "$bundle/disabled-public-preview"; fi
  exit "$rc"
}
trap rollback ERR
curl -fsS --max-time 8 --resolve filyx.fr:443:127.0.0.1 https://filyx.fr/assets/previews/gtavi-lenzo-test-20261118/index.html -o "$bundle/served.html"
cmp -s index.html "$bundle/served.html"
curl -fsS --max-time 8 --resolve filyx.fr:443:127.0.0.1 https://filyx.fr/assets/previews/gtavi-lenzo-test-20261118/simulation.js -o "$bundle/served.js"
cmp -s simulation.js "$bundle/served.js"
after="$(php "$bundle/presentation.php" | sha256sum | cut -d ' ' -f 1)"
[[ "$before" == "$after" ]]
trap - ERR
printf 'Simulation publique installée. GTAVI réel et présentation inchangés. Aucun message bot envoyé.\n'
