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

if [[ ${EUID} -ne 0 ]]; then
  printf '%s\n' "reset-data must run as root" >&2
  exit 1
fi
exec 9>/run/lock/harbor-release.lock
if ! flock -n 9; then
  printf '%s\n' "another release or rollback is in progress" >&2
  exit 1
fi

skip_backup=0
yes_flag=0
for a in "$@"; do
  case "$a" in
    --yes) yes_flag=1 ;;
    --skip-backup) skip_backup=1 ;;
    *)
      printf '%s\n' "unknown argument: $a" >&2
      exit 1
      ;;
  esac
done
if [[ "$yes_flag" != 1 ]]; then
  printf '%s\n' "usage: reset-data.sh --yes [--skip-backup]" >&2
  printf '%s\n' "this permanently deletes all Mongo, Redis, and MinIO data" >&2
  exit 1
fi

compose=(docker compose --env-file /etc/harbor/harbor.env -f /opt/harbor/deploy/compose/docker-compose.yml)

if [[ "$skip_backup" == 1 ]]; then
  printf '%s\n' "--skip-backup given: NOT taking a safety backup before wiping data"
else
  printf '%s\n' "taking a safety backup before wiping data (use --skip-backup to skip)"
  set -a
  # shellcheck disable=SC1091
  . /etc/harbor/harbor.env
  set +a
  if ! BACKUP_DIR=/var/backups/harbor BACKUP_STATUS_DIR=/opt/harbor/deploy/backup/status \
      /opt/harbor/deploy/backup/backup.sh; then
    printf '%s\n' "pre-reset backup failed — aborting without touching any data" >&2
    printf '%s\n' "re-run with --skip-backup if you really want to proceed without one" >&2
    exit 1
  fi
fi

printf '%s\n' "stopping app slots"
for slot in blue green; do
  systemctl stop "harbor-gateway@$slot.service" 2>/dev/null || true
  systemctl stop "harbor-worker@$slot.service" 2>/dev/null || true
done

printf '%s\n' "stopping data services"
"${compose[@]}" stop mongo redis minio
"${compose[@]}" rm -f mongo redis minio

printf '%s\n' "removing data volumes"
docker volume rm haixun-prod_mongo_data haixun-prod_mongo_config haixun-prod_redis_data haixun-prod_minio_data

printf '%s\n' "recreating empty data services"
"${compose[@]}" up -d --wait --wait-timeout 180 mongo redis minio

rm -f /etc/harbor/admin-seeded /etc/harbor/initial-admin-credentials

printf '%s\n' "data reset complete: mongo/redis/minio are now empty"
printf '%s\n' "monitoring volumes (prometheus/grafana/loki/alertmanager) were left untouched"
if [[ "$skip_backup" != 1 ]]; then
  printf '%s\n' "pre-reset safety backup is under /var/backups/harbor (see backup.sh output above for the exact timestamp)"
fi
printf '%s\n' "next: run release.sh to redeploy app code, run forward migrations, and reseed the admin account"
