#!/bin/bash

set -euo pipefail

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

SERVER_HOST="116.62.17.81"
SERVER_PORT="9444"
SERVER_USERNAME="wkc"
SERVER_PASSWORD="wkc@0825"
REMOTE_ROOT="/volume1/webapp/ccdi"
TONGWEB_HOME="${TONGWEB_HOME:-/opt/TongWeb}"
APP_NAME="${APP_NAME:-ruoyi-admin}"
DRY_RUN="false"

ensure_command() {
  local command_name="$1"
  if ! command -v "${command_name}" >/dev/null 2>&1; then
    echo "缺少命令: ${command_name}" >&2
    exit 1
  fi
}

ensure_paramiko() {
  if python3 - <<'PY'
import importlib.util
import sys

sys.exit(0 if importlib.util.find_spec("paramiko") else 1)
PY
  then
    return
  fi

  python3 -m pip install --user paramiko
}

POSITION=0
for arg in "$@"; do
  if [[ "${arg}" == "--dry-run" ]]; then
    DRY_RUN="true"
    continue
  fi

  POSITION=$((POSITION + 1))
  case "${POSITION}" in
    1) SERVER_HOST="${arg}" ;;
    2) SERVER_PORT="${arg}" ;;
    3) SERVER_USERNAME="${arg}" ;;
    4) SERVER_PASSWORD="${arg}" ;;
    5) REMOTE_ROOT="${arg}" ;;
    6) TONGWEB_HOME="${arg}" ;;
    7) APP_NAME="${arg}" ;;
    *)
      echo "仅支持 [host] [port] [username] [password] [remoteRoot] [tongwebHome] [appName] [--dry-run]" >&2
      exit 1
      ;;
  esac
done

if [[ "${DRY_RUN}" == "true" ]]; then
  echo "[DryRun] TongWeb NAS 部署参数预览"
  echo "Host: ${SERVER_HOST}"
  echo "Port: ${SERVER_PORT}"
  echo "Username: ${SERVER_USERNAME}"
  echo "RemoteRoot: ${REMOTE_ROOT}"
  echo "TongWebHome: ${TONGWEB_HOME}"
  echo "AppName: ${APP_NAME}"
  exit 0
fi

echo "[1/4] 检查本地环境"
ensure_command "mvn"
ensure_command "python3"

echo "[2/4] 打包后端 war"
(
  cd "${REPO_ROOT}"
  mvn -pl ruoyi-admin -am package -DskipTests
)

WAR_PATH="${REPO_ROOT}/ruoyi-admin/target/ruoyi-admin.war"
if [[ ! -f "${WAR_PATH}" ]]; then
  echo "未找到后端 war 包: ${WAR_PATH}" >&2
  exit 1
fi

echo "[3/4] 检查远端执行依赖"
ensure_paramiko

echo "[4/4] 上传 war 并重启 TongWeb"
python3 "${SCRIPT_DIR}/remote-deploy-tongweb.py" \
  --host "${SERVER_HOST}" \
  --port "${SERVER_PORT}" \
  --username "${SERVER_USERNAME}" \
  --password "${SERVER_PASSWORD}" \
  --local-war "${WAR_PATH}" \
  --remote-root "${REMOTE_ROOT}" \
  --tongweb-home "${TONGWEB_HOME}" \
  --app-name "${APP_NAME}"
