#!/usr/bin/env bash
# 全部清除 → 起 infra → migrate → build → start
# 用法：
#   ./deploy/scripts/redeploy.sh --yes
#   ./deploy/scripts/redeploy.sh --yes --kill-orphan
#   ./deploy/scripts/redeploy.sh --yes --keep-data   # 不清 volume，只重裝 app
set -euo pipefail
# shellcheck source=_common.sh
source "$(cd "$(dirname "$0")" && pwd)/_common.sh"

YES=0
KEEP_DATA=0
KILL_ORPHAN=0
for a in "$@"; do
  case "$a" in
    --yes|-y) YES=1 ;;
    --keep-data) KEEP_DATA=1 ;;
    --kill-orphan) KILL_ORPHAN=1 ;;
    -h|--help)
      cat <<EOF
完整重部署 Harbor Desk（apps/backend + apps/web + infra）

  $0 --yes                 清資料 + 重建 + 啟動
  $0 --yes --keep-data     保留 Mongo/Redis/MinIO 資料，只重裝 app
  $0 --yes --kill-orphan   wipe 時清掉殘留 worker

流程：
  1) stop apps
  2) wipe infra volumes（除非 --keep-data）
  3) up-infra
  4) migrate（不建立預設帳號）
  5) build
  6) start gateway + vite
EOF
      exit 0
      ;;
  esac
done

[[ "$YES" == "1" ]] || die "請加 --yes 確認（會影響執行中服務；預設還會刪資料）"

load_env

if [[ "$KEEP_DATA" == "1" ]]; then
  log "=== keep-data: stop apps only ==="
  "$DEPLOY_DIR/scripts/stop.sh"
else
  WIPE_ARGS=(--yes)
  [[ "$KILL_ORPHAN" == "1" ]] && WIPE_ARGS+=(--kill-orphan)
  "$DEPLOY_DIR/scripts/wipe.sh" "${WIPE_ARGS[@]}"
fi

"$DEPLOY_DIR/scripts/up-infra.sh"
"$DEPLOY_DIR/scripts/migrate.sh"
"$DEPLOY_DIR/scripts/build.sh"
"$DEPLOY_DIR/scripts/start.sh"

log ""
log "=== redeploy complete ==="
"$DEPLOY_DIR/scripts/status.sh" || true
