#!/usr/bin/env bash
# Restore the databases + filestore from a deploy.sh backup, and put the code
# back to the commit that backup was taken at.
#
#   rollback.sh              restore the last backup
#   rollback.sh 20260801-143000
#
# An Odoo -u migration is not reversible by re-checking-out the old code: the
# schema has already moved. Restoring the dump is the only honest rollback.
set -Eeuo pipefail

DEPLOY_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$DEPLOY_DIR"
set -a; . ./.env; set +a

DC="docker compose -f $DEPLOY_DIR/docker-compose.yml"
STAMP="${1:-$(cat "$BACKUP_DIR/LAST_GOOD")}"
SRC="$BACKUP_DIR/$STAMP"

[[ -d "$SRC" ]] || { echo "no backup at $SRC"; exit 1; }

echo "About to overwrite all databases from $SRC. This destroys anything"
echo "written since $STAMP, including tenant sales."
read -r -p "Type the stamp to confirm: " confirm
[[ "$confirm" == "$STAMP" ]] || { echo "aborted"; exit 1; }

$DC stop odoo odoo-cp

for dump in "$SRC"/*.dump; do
  db="$(basename "$dump" .dump)"
  echo "==> Restoring $db"
  $DC exec -T db psql -U "$DB_USER" -d postgres -c \
    "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='$db';" >/dev/null
  $DC exec -T db psql -U "$DB_USER" -d postgres -c "DROP DATABASE IF EXISTS \"$db\";"
  $DC exec -T db psql -U "$DB_USER" -d postgres -c "CREATE DATABASE \"$db\" OWNER \"$DB_USER\";"
  $DC exec -T db pg_restore -U "$DB_USER" -d "$db" "/backups/$STAMP/$db.dump"
done

if [[ -f "$SRC/filestore.tar.gz" ]]; then
  echo "==> Restoring filestore"
  docker run --rm -v nacef_filestore:/fs -v "$SRC":/in alpine \
    sh -c 'rm -rf /fs/* && tar xzf /in/filestore.tar.gz -C /fs'
fi

if [[ -f "$SRC/COMMIT" ]]; then
  echo "==> Restoring code to $(cat "$SRC/COMMIT")"
  git -C "$CODE_DIR" checkout --force "$(cat "$SRC/COMMIT")"
fi

$DC up -d
echo "Rolled back to $STAMP"
