#!/usr/bin/env bash
# Devwebs restore: loads a backup made by backup.sh into a database, restores uploaded files, then checks tenant
# isolation. Stop the API and workers first.
#
#   DB_HOST=... DB_USER=... DB_PASSWORD=... DB_NAME=devwebs_restored STORAGE_DIR=/opt/devwebs/backend/storage \
#   deploy/scripts/restore.sh /var/backups/devwebs/devwebs-20261015T020000Z
#
# The target database must exist and be empty (restore into a new one, check it, then switch DB_NAME).
set -euo pipefail
base="${1:?Usage: restore.sh <backup path without extension>}"
: "${DB_NAME:?Set DB_NAME (the database to restore into)}" "${DB_USER:=devwebs}" "${DB_HOST:=127.0.0.1}" "${DB_PORT:=3306}"
: "${STORAGE_DIR:=./backend/storage}"
CLIENT="${MYSQL:-$(command -v mysql || command -v mariadb)}"

if [ -f "$base.sha256" ]; then
  ( cd "$(dirname "$base")" && sha256sum -c "$(basename "$base").sha256" )
fi

cnf="$(mktemp)"
trap 'rm -f "$cnf"' EXIT
chmod 600 "$cnf"
printf '[client]\nuser=%s\npassword=%s\nhost=%s\nport=%s\n' "$DB_USER" "${DB_PASSWORD:-}" "$DB_HOST" "$DB_PORT" > "$cnf"

tables="$("$CLIENT" --defaults-extra-file="$cnf" -N -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$DB_NAME'")"
if [ "$tables" != "0" ]; then
  echo "Database $DB_NAME is not empty ($tables tables). Restore into a new, empty database." >&2
  exit 1
fi

echo "Loading $base.sql.gz into $DB_NAME..."
gunzip -c "$base.sql.gz" | "$CLIENT" --defaults-extra-file="$cnf" --default-character-set=utf8mb4 "$DB_NAME"

if [ -f "$base-storage.tar.gz" ]; then
  echo "Restoring files into $STORAGE_DIR..."
  mkdir -p "$STORAGE_DIR"
  tar -C "$STORAGE_DIR" -xzf "$base-storage.tar.gz"
fi

triggers="$("$CLIENT" --defaults-extra-file="$cnf" -N -e "SELECT COUNT(*) FROM information_schema.triggers WHERE trigger_schema='$DB_NAME'")"
echo "Restored. Tenancy triggers present: $triggers"
if [ "$triggers" = "0" ]; then
  echo "WARNING: no triggers were restored. Was the dump made with --triggers?" >&2
  exit 1
fi
echo "Next: run 'node dist/cli.js tenancy:check' (or npm run tenancy:check) with DB_NAME=$DB_NAME, then point the app at it."
