#!/bin/bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
STAGE_ROOT="${REPO_ROOT}/.deploy/ccdi-package"

SERVER_HOST="116.62.17.81"
SERVER_PORT="9444"
SERVER_USERNAME="wkc"
SERVER_PASSWORD="wkc@0825"
REMOTE_ROOT="/volume1/webapp/ccdi"
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
}

reset_directory() {
  local target_dir="$1"
  rm -rf "${target_dir}"
  mkdir -p "${target_dir}"
}

copy_path() {
  local source_path="$1"
  local destination_path="$2"
  cp -R "${source_path}" "${destination_path}"
}

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}" ;;
    *)
      echo "仅支持 [host] [port] [username] [password] [remoteRoot] [--dry-run]" >&2
      exit 1
      ;;
  esac
done

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

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

echo "[2/5] 打包后端"
(
  cd "${REPO_ROOT}"
  mvn clean package -DskipTests
)

echo "[3/5] 打包前端"
(
  cd "${REPO_ROOT}/ruoyi-ui"
  npm run build:prod
)

echo "[4/5] 组装部署目录"
reset_directory "${STAGE_ROOT}"
mkdir -p "${STAGE_ROOT}/backend" "${STAGE_ROOT}/frontend"

copy_path "${REPO_ROOT}/docker" "${STAGE_ROOT}/docker"
copy_path "${REPO_ROOT}/lsfx-mock-server" "${STAGE_ROOT}/lsfx-mock-server"
copy_path "${REPO_ROOT}/ruoyi-ui/dist" "${STAGE_ROOT}/frontend/dist"
copy_path "${REPO_ROOT}/docker-compose.yml" "${STAGE_ROOT}/docker-compose.yml"
copy_path "${REPO_ROOT}/.env.example" "${STAGE_ROOT}/.env.example"
copy_path "${REPO_ROOT}/ruoyi-admin/target/ruoyi-admin.jar" "${STAGE_ROOT}/backend/ruoyi-admin.jar"
python3 "${SCRIPT_DIR}/render_nas_env.py" \
  --template "${REPO_ROOT}/.env.example" \
  --output "${STAGE_ROOT}/.env"

echo "[5/5] 上传并远端部署"
ensure_paramiko

python3 "${SCRIPT_DIR}/remote-deploy.py" \
  --host "${SERVER_HOST}" \
  --port "${SERVER_PORT}" \
  --username "${SERVER_USERNAME}" \
  --password "${SERVER_PASSWORD}" \
  --local-root "${STAGE_ROOT}" \
  --remote-root "${REMOTE_ROOT}"
