#!/usr/bin/env bash
# 全部清除：停 app + infra 容器 + volumes（Mongo/Redis/MinIO 資料全沒）
# 用法：./deploy/scripts/wipe.sh --yes
set -euo pipefail
# shellcheck source=_common.sh
source "$(cd "$(dirname "$0")" && pwd)/_common.sh"

YES=0
KILL_ORPHAN=0
for a in "$@"; do
  case "$a" in
    --yes|-y) YES=1 ;;
    --kill-orphan) KILL_ORPHAN=1 ;;
    -h|--help)
      cat <<EOF
用法: $0 --yes [--kill-orphan]

  --yes           確認刪除（必填）
  --kill-orphan   一併杀掉宿主上殘留的 old worker / 多餘 gateway
EOF
      exit 0
      ;;
  esac
done

[[ "$YES" == "1" ]] || die "這會刪除 Mongo/Redis/MinIO 全部資料。請加 --yes"

load_env
require_cmd docker

log "=== WIPE: stop apps ==="
"$DEPLOY_DIR/scripts/stop.sh" || true

if [[ "$KILL_ORPHAN" == "1" ]]; then
  log "=== kill orphan workers / gateways under apps/backend ==="
  # 只殺本 repo 的 bin，避免誤殺系統程序
  pkill -f "$BACKEND_DIR/bin/worker" 2>/dev/null || true
  pkill -f "$BACKEND_DIR/bin/gateway" 2>/dev/null || true
  pkill -f "$ROOT_DIR/old/backend/bin/" 2>/dev/null || true
  sleep 0.5
fi

log "=== WIPE: docker compose down -v (haixun-infra) ==="
# 新 compose
compose down -v --remove-orphans 2>/dev/null || true
# 舊路徑同名 project 也清
if [[ -f "$ROOT_DIR/old/infra/docker-compose.yml" ]]; then
  docker compose --env-file "$ENV_FILE_RESOLVED" \
    -f "$ROOT_DIR/old/infra/docker-compose.yml" \
    down -v --remove-orphans 2>/dev/null || true
fi

# 殘餘 volume 名稱
for v in haixun-infra_mongo_data haixun-infra_redis_data haixun-infra_minio_data \
         mongo_data redis_data minio_data; do
  docker volume rm "$v" 2>/dev/null || true
done

rm -f "$RUN_DIR"/*.pid 2>/dev/null || true
log "wipe done — 資料已清空，infra 已停"
