#!/bin/bash
set -euo pipefail

root_dir="$(cd "$(dirname "$0")/.." && pwd)"
snapshot="${1:-}"
if [[ -z "$snapshot" || ! -f "$snapshot" || "$(basename "$snapshot")" != code-*.tar.gz ]]; then
  echo "Usage: $0 storage/releases/code-VERSION-DATE.tar.gz" >&2
  exit 2
fi
case "$(realpath "$snapshot")" in "$root_dir"/storage/releases/*) ;; *) echo "Snapshot hors de storage/releases refusé." >&2; exit 2;; esac
touch "$root_dir/storage/maintenance.flag"
trap 'rm -f "$root_dir/storage/maintenance.flag"' EXIT
tar -xzf "$snapshot" -C "$root_dir"
php "$root_dir/scripts/migrate.php"
rm -f "$root_dir/storage/maintenance.flag"
echo "Code restauré. La base n’a pas été rétrogradée automatiquement."
