#!/usr/bin/env bash
# Docker deployment script with safety checks
set -euo pipefail

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

prompt_yes_no() {
  local prompt="$1"
  local choice_hint="${2:-[y/N]}"
  local answer
  read -r -p "$prompt $choice_hint " answer || true
  answer="${answer:-}"
  answer="$(printf '%s' "$answer" | tr '[:upper:]' '[:lower:]')"
  [[ "$answer" == "y" || "$answer" == "yes" ]]
}

echo "=== 部署前检查开始 ==="

if ! git -C "$SCRIPT_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  echo "错误: 当前目录不在 Git 仓库内，无法继续。"
  exit 1
fi

CURRENT_BRANCH=$(git -C "$SCRIPT_DIR" rev-parse --abbrev-ref HEAD)
if [[ "$CURRENT_BRANCH" != "master" ]]; then
  echo "错误: 当前分支为 '$CURRENT_BRANCH'。仅允许在 master 分支上部署。"
  exit 1
fi

if prompt_yes_no "你跑测试了吗？确认已跑请输入 y"; then
  echo "已确认测试执行完毕。"
else
  if prompt_yes_no "需要我帮你跑测试吗？"; then
    echo "开始执行测试: mvn test"
    if ! mvn test; then
      echo "测试未通过，部署流程终止。"
      exit 1
    fi
    echo "测试通过。"
  else
    echo "错误: 未执行测试，部署流程终止。"
    exit 1
  fi
fi

if ! prompt_yes_no "你备份数据库了吗？确认已备份请输入 y"; then
  echo "请先完成数据库备份，再运行部署脚本。"
  exit 1
fi

if ! prompt_yes_no "你 commit 了吗？确认已提交请输入 y"; then
  echo "请在提交后再运行部署脚本。"
  exit 1
fi

if ! git -C "$SCRIPT_DIR" diff --quiet; then
  echo "错误: 检测到未暂存的本地修改，请处理后再试。"
  exit 1
fi

if [[ -n "$(git -C "$SCRIPT_DIR" ls-files --others --exclude-standard)" ]]; then
  echo "错误: 检测到未跟踪的文件，请清理或加入版本控制后再试。"
  exit 1
fi

if ! git -C "$SCRIPT_DIR" diff --cached --quiet; then
  echo "错误: 检测到未提交的暂存修改，请提交后再试。"
  exit 1
fi

echo "部署前检查通过。"

# Get current time and format it
current_time=$(date +"%Y-%m-%d %H:%M:%S")
echo "Deployment started at: $current_time"

echo "Connecting to server to update docker container..."
# SSH into the server, pull the latest image and restart the container
ssh root@122.51.20.105 "source /etc/profile; cd ~; docker compose pull && docker compose up -d"
echo "Docker container updated!"

# Get current time and format it
current_time=$(date +"%Y-%m-%d %H:%M:%S")
echo "Deployment finished at: $current_time"
