#!/usr/bin/env bash
# ============================================================
# restore.sh — restaure TON CONTENU sur le serveur de prod
#
# A lancer SUR LE SERVEUR, apres avoir demarre la stack prod
# (docker compose -f docker-compose.prod.yml up -d) et transfere
# les 2 fichiers de backup dans ./backups/.
#
# Usage :
#   bash scripts/restore.sh backups/db-XXXX.sql.gz backups/uploads-XXXX.tar.gz
#
# Conteneurs prod (override si besoin) :
#   PG_CONTAINER=... DIRECTUS_CONTAINER=... bash scripts/restore.sh ...
# ============================================================
set -euo pipefail

cd "$(dirname "$0")/.."

DB_DUMP="${1:?Chemin du dump DB requis (ex: backups/db-XXXX.sql.gz)}"
UPLOADS_TAR="${2:?Chemin de l archive uploads requis (ex: backups/uploads-XXXX.tar.gz)}"

if [ -f .env ]; then set -a; . ./.env; set +a; fi

PG_CONTAINER="${PG_CONTAINER:-mostuki-postgres}"
DIRECTUS_CONTAINER="${DIRECTUS_CONTAINER:-mostuki-directus}"
PG_USER="${POSTGRES_USER:-directus}"
PG_DB="${POSTGRES_DB:-directus}"

echo "ATTENTION : ceci ECRASE la base '$PG_DB' et les photos du serveur."
read -r -p "Continuer ? (tape oui) " ans
[ "$ans" = "oui" ] || { echo "Annule."; exit 1; }

echo "==> Restauration base Postgres ($PG_CONTAINER)"
# Recree un schema propre avant import pour eviter les doublons
docker exec -i "$PG_CONTAINER" psql -U "$PG_USER" -d "$PG_DB" \
  -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;"
gunzip -c "$DB_DUMP" | docker exec -i "$PG_CONTAINER" psql -U "$PG_USER" -d "$PG_DB"

echo "==> Restauration des photos (uploads Directus)"
docker exec -i "$DIRECTUS_CONTAINER" sh -c 'rm -rf /directus/uploads/* && tar xzf - -C /directus/uploads' < "$UPLOADS_TAR"

echo ""
echo "OK. Redemarre Directus pour qu'il reprenne la base restauree :"
echo "  docker compose -f docker-compose.prod.yml restart directus astro"
