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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"

usage() {
  cat <<'USAGE'
Usage:
  scripts/reset-prelaunch-chain-data.sh
  sudo scripts/reset-prelaunch-chain-data.sh --apply --i-understand-this-resets-vexon-chain

Moves Vexon prelaunch node chain data into a timestamped backup directory so a
server can start from a final mainnet binary and final tokenomics ledger.

Dry-run is the default. The script never touches:
  - /root/.vexonwallet
  - wallet seeds or wallet.db
  - existing pool paths
  - database contents

Options:
  --apply                                Move the planned paths.
  --i-understand-this-resets-vexon-chain Required with --apply.
  -h, --help                             Show this help.
USAGE
}

apply=0
confirmed=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --apply)
      apply=1
      ;;
    --i-understand-this-resets-vexon-chain)
      confirmed=1
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown option: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
  shift
done

if [[ -f .env ]]; then
  set -a
  # shellcheck source=/dev/null
  source .env
  set +a
fi

VEX_NODE_APPDATA="${VEX_NODE_APPDATA:-/root/.vexond}"
VEX_PEER_APPDATA="${VEX_PEER_APPDATA:-/root/.vexond-peer}"
VEX_WALLET_APPDATA="${VEX_WALLET_APPDATA:-/root/.vexonwallet}"
VEX_PRELAUNCH_RESET_BACKUP_DIR="${VEX_PRELAUNCH_RESET_BACKUP_DIR:-/root/vexon-prelaunch-chain-backups}"

timestamp="$(date +%Y%m%d-%H%M%S)"
backup_dir="$VEX_PRELAUNCH_RESET_BACKUP_DIR/$timestamp"
plan_file="$(mktemp)"
trap 'rm -f "$plan_file"' EXIT

die() {
  printf '[FAIL] %s\n' "$1" >&2
  exit 1
}

plan_path() {
  local label="$1"
  local base="$2"
  local rel="$3"
  local src="$base/$rel"
  local dst="$backup_dir/$label/$rel"

  if [[ -e "$src" ]]; then
    printf '%s\t%s\t%s\n' "$label" "$src" "$dst" >> "$plan_file"
  fi
}

plan_appdata() {
  local label="$1"
  local base="$2"

  [[ -d "$base" ]] || return 0

  plan_path "$label" "$base" mainnet
  plan_path "$label" "$base" testnet
  plan_path "$label" "$base" testnet2
  plan_path "$label" "$base" simnet
  plan_path "$label" "$base" regnet
  plan_path "$label" "$base" logs
  plan_path "$label" "$base" peers.json
  plan_path "$label" "$base" banlist.json
}

plan_appdata node "$VEX_NODE_APPDATA"
plan_appdata peer "$VEX_PEER_APPDATA"

echo "== Vexon prelaunch chain-data reset plan =="
date
echo
echo "Node appdata:   $VEX_NODE_APPDATA"
echo "Peer appdata:   $VEX_PEER_APPDATA"
echo "Wallet appdata: $VEX_WALLET_APPDATA (not touched)"
echo "Backup dir:     $backup_dir"
echo

if [[ ! -s "$plan_file" ]]; then
  echo "[OK] no node chain data paths found to move"
  exit 0
fi

printf '%-8s  %-55s  %s\n' "SCOPE" "SOURCE" "BACKUP"
while IFS=$'\t' read -r label src dst; do
  printf '%-8s  %-55s  %s\n' "$label" "$src" "$dst"
done < "$plan_file"

echo
if (( apply == 0 )); then
  echo "[DRY-RUN] no files were moved."
  echo "Run with --apply --i-understand-this-resets-vexon-chain after final binaries are ready."
  exit 0
fi

[[ "$(id -u)" == "0" ]] || die "apply mode must run as root"
(( confirmed == 1 )) || die "--apply requires --i-understand-this-resets-vexon-chain"

echo "Stopping Vexon services and screen sessions..."
if command -v systemctl >/dev/null 2>&1; then
  systemctl stop vexon-stratum.service vexon-node-peer.service vexon-node.service >/dev/null 2>&1 || true
fi

if command -v screen >/dev/null 2>&1; then
  screen -S "${VEX_STRATUM_SCREEN:-Vexon_Stratum}" -X quit >/dev/null 2>&1 || true
  screen -S "${VEX_PEER_SCREEN:-Vexon_Node_Peer}" -X quit >/dev/null 2>&1 || true
  screen -S "${VEX_NODE_SCREEN:-Vexon_Node}" -X quit >/dev/null 2>&1 || true
fi

mkdir -p "$backup_dir"

while IFS=$'\t' read -r _label src dst; do
  mkdir -p "$(dirname "$dst")"
  mv -v "$src" "$dst"
done < "$plan_file"

chmod -R go-rwx "$backup_dir"

echo
echo "[OK] Vexon prelaunch node chain data moved to $backup_dir"
echo "Install final binaries, then restart:"
echo "  sudo systemctl restart vexon-node vexon-node-peer vexon-stratum"
echo "  scripts/repair-vex-coin.sh"
echo "  scripts/health-check.sh"
