#!/bin/bash
set -Eeuo pipefail
umask 027
bundle="$(realpath "${1:?Dossier de test attendu}")"
[[ $EUID -eq 0 && "$bundle" == /tmp/filyx-giveaway-options.* ]]
target=/srv/filyx/apps/web/app/Services/GiveawayEntryService.php
source="$bundle/stage/apps/web/app/Services/GiveawayEntryService.php"
exec 9>/var/lock/filyx-giveaway-registration-deploy.lock
flock -n 9
[[ "$(sha256sum "$target" | cut -d' ' -f1)" == 480ca9bf033e4994b742f61dbdf06c65fda9578def8f0723609890fc21b50af5 ]]
php -l "$source"
! grep -q 'strtotime' "$source"
grep -q 'AS deadline_open' "$source"
grep -q 'AS still_valid' "$source"
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 ]]
backup="/var/backups/filyx/giveaway-registration-time-$(date -u +%Y%m%d-%H%M%S)"
install -d -m 0700 "$backup"
cp -a -- "$target" "$backup/GiveawayEntryService.php"
swap() {
  local temp
  temp="$(mktemp -- "$target.registration.XXXXXX")"
  install -o root -g root -m 0644 -- "$1" "$temp"
  mv -f -- "$temp" "$target"
}
rollback() { local rc=$?; trap - ERR; swap "$backup/GiveawayEntryService.php"; exit "$rc"; }
trap rollback ERR
swap "$source"
[[ "$(sha256sum "$target" | cut -d' ' -f1)" == "$(sha256sum "$source" | cut -d' ' -f1)" ]]
[[ "$(probe /login)" == 200 && "$(probe /api/giveaways/9/entries)" == 401 ]]
trap - ERR
printf 'Correctif horaires publié. Aucun réglage, inscription ou solde modifié ; aucun message envoyé. Sauvegarde : %s\n' "$backup"
