#!/usr/bin/env bash
set -euo pipefail

DRY_RUN=1
BACKUP_PATH=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --confirm)
      DRY_RUN=0
      shift
      ;;
    --backup)
      BACKUP_PATH="${2:-}"
      shift 2
      ;;
    --help|-h)
      cat <<'HELP'
GAL-2 Time Contract rollback script

Default mode:
  dry-run only

Usage:
  ./rollback_from_backup.sh --backup /path/to/backup
  ./rollback_from_backup.sh --backup /path/to/backup --confirm

Safety:
  Actual rollback requires:
    --confirm
    GAL2_ALLOW_DESTRUCTIVE=1

Supported backup format:
  directory containing usr/local/gal2 and optionally etc/gal2
HELP
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      exit 2
      ;;
  esac
done

if [[ -z "$BACKUP_PATH" ]]; then
  echo "ERROR: --backup path is required" >&2
  exit 2
fi

if [[ ! -d "$BACKUP_PATH" ]]; then
  echo "ERROR: backup path is not a directory: $BACKUP_PATH" >&2
  exit 3
fi

if [[ "$DRY_RUN" -eq 0 && "${GAL2_ALLOW_DESTRUCTIVE:-0}" != "1" ]]; then
  echo "ERROR: destructive mode requires GAL2_ALLOW_DESTRUCTIVE=1" >&2
  exit 4
fi

if [[ "$DRY_RUN" -eq 0 && "$(id -u)" -ne 0 ]]; then
  echo "ERROR: destructive mode must be run as root via sudo" >&2
  exit 5
fi

run() {
  if [[ "$DRY_RUN" -eq 1 ]]; then
    echo "DRY_RUN: $*"
  else
    "$@"
  fi
}

echo "GAL-2 rollback"
echo "dry_run=$DRY_RUN"
echo "backup_path=$BACKUP_PATH"
echo ""

if [[ -d "$BACKUP_PATH/usr/local/gal2" ]]; then
  run mkdir -p /usr/local
  run rm -rf /usr/local/gal2
  run cp -a "$BACKUP_PATH/usr/local/gal2" /usr/local/gal2
else
  echo "WARN: backup does not contain usr/local/gal2"
fi

if [[ -d "$BACKUP_PATH/etc/gal2" ]]; then
  run mkdir -p /etc
  run rm -rf /etc/gal2
  run cp -a "$BACKUP_PATH/etc/gal2" /etc/gal2
else
  echo "INFO: backup does not contain etc/gal2"
fi

echo "DONE"
