#!/bin/bash
# Gitea post-receive hook: 自动部署 cma-management
# 每次 push 到 main 分支后，通过 SSH 到宿主机执行部署
#
# 工作原理：
#   1. 从 stdin 读取 git push 信息 (oldrev newrev refname)
#   2. 检查是否 push 到 main 分支
#   3. 通过 SSH 到宿主机 (172.17.0.1) 执行 git pull + deploy.sh

set -e

HOST="172.17.0.1"
SSH_KEY="/root/.ssh/id_ed25519"
SSH_CMD="ssh -i ${SSH_KEY} -o StrictHostKeyChecking=no -o ConnectTimeout=10 root@${HOST}"

while read oldrev newrev refname; do
  # 只处理 main 分支的 push
  if [ "$refname" = "refs/heads/main" ]; then
    echo "[deploy-hook] 检测到 main 分支推送: ${oldrev:0:8}..${newrev:0:8}"
    echo "[deploy-hook] 通过 SSH 连接宿主机执行部署..."

    ${SSH_CMD} '
      echo "[deploy-hook] 进入 cma-management 目录"
      cd /root/cma-management || exit 1

      echo "[deploy-hook] 拉取最新代码..."
      git pull origin main 2>&1

      echo "[deploy-hook] 运行部署脚本..."
      bash deploy.sh 2>&1

      echo "[deploy-hook] 部署完成"
    ' 2>&1

    rc=$?
    if [ $rc -eq 0 ]; then
      echo "[deploy-hook] ✓ 部署成功"
    else
      echo "[deploy-hook] ✗ 部署失败 (exit code: $rc)"
      exit $rc
    fi
  fi
done
