#!/usr/bin/env bash
# ════════════════════════════════════════════════════════════════
# 光湖 · 服务器初始化第一步 · 找仓库 + 拉代码 + 装Runner
# 专供冰朔在腾讯云在线终端执行
# ════════════════════════════════════════════════════════════════

# 这个脚本是"傻瓜式"的，一步一步来，每步都有说明
# 如果某步报错，不要慌，把报错信息发给铸渊

set +e  # 不自动退出，让冰朔看到错误

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

echo -e "${CYAN}═══════════════════════════════════════════${NC}"
echo -e "${CYAN}  光湖 · 服务器初始化 · 第一步${NC}"
echo -e "${CYAN}═══════════════════════════════════════════${NC}"
echo ""

# ─── 第1步：找到仓库 ──────────────────────────────────────────
echo -e "${YELLOW}[第1步] 查找仓库位置...${NC}"
REPO_PATH=""

# 常见位置逐一检查
for p in \
  "/data/guanghulab" \
  "/data/guanghulab/guanghulab" \
  "/opt/guanghulab" \
  "/opt/zhuyuan" \
  "/root/guanghulab" \
  "/home/guanghulab"
do
  if [[ -d "$p/.git" ]]; then
    REPO_PATH="$p"
    echo -e "${GREEN}  找到了！仓库在: $p${NC}"
    break
  fi
done

if [[ -z "$REPO_PATH" ]]; then
  echo -e "${YELLOW}  没找到仓库，搜索中...${NC}"
  FOUND=$(find / -name ".git" -type d -path "*/guanghulab/.git" 2>/dev/null | head -3)
  if [[ -n "$FOUND" ]]; then
    REPO_PATH=$(dirname "$FOUND" | head -1)
    echo -e "${GREEN}  找到了！仓库在: $REPO_PATH${NC}"
  else
    echo -e "${YELLOW}  服务器上没有仓库，需要克隆。${NC}"
    echo ""
    echo -e "${CYAN}  创建目录并克隆...${NC}"
    mkdir -p /data/guanghulab
    cd /data/guanghulab
    git clone https://bingshuo:3e16b79c427bb44b77c00b319aa641bde8f61d84@guanghulab.com/git/bingshuo/guanghulab.git .
    if [[ $? -eq 0 ]]; then
      REPO_PATH="/data/guanghulab"
      echo -e "${GREEN}  克隆成功！${NC}"
    else
      echo -e "${YELLOW}  克隆失败，可能是网络问题。尝试备用方案...${NC}"
      # 备用：直接下载最新代码压缩包
      curl -sL -o /tmp/guanghulab.tar.gz \
        "https://guanghulab.com/git/api/v1/repos/bingshuo/guanghulab/archive/main.tar.gz" \
        -H "Authorization: token 3e16b79c427bb44b77c00b319aa641bde8f61d84"
      if [[ -f /tmp/guanghulab.tar.gz && -s /tmp/guanghulab.tar.gz ]]; then
        mkdir -p /data/guanghulab
        cd /data/guanghulab
        tar xzf /tmp/guanghulab.tar.gz --strip-components=1
        REPO_PATH="/data/guanghulab"
        # 初始化git（从压缩包来的没有.git）
        git init
        git remote add origin "https://bingshuo:3e16b79c427bb44b77c00b319aa641bde8f61d84@guanghulab.com/git/bingshuo/guanghulab.git"
        git add -A
        git commit -m "init from archive"
        echo -e "${GREEN}  从压缩包恢复成功！${NC}"
      else
        echo "❌ 克隆和压缩包都失败了，请把这段输出截图发给铸渊"
        exit 1
      fi
    fi
  fi
fi

# ─── 第2步：拉取最新代码 ──────────────────────────────────────
echo ""
echo -e "${YELLOW}[第2步] 拉取最新代码...${NC}"
cd "$REPO_PATH"
git fetch origin
git reset --hard origin/main
echo -e "${GREEN}  代码已更新到最新版本${NC}"

# ─── 第3步：确认脚本存在 ──────────────────────────────────────
echo ""
echo -e "${YELLOW}[第3步] 检查Runner安装脚本...${NC}"
if [[ -f "$REPO_PATH/scripts/gitea-runner/install-runner.sh" ]]; then
  echo -e "${GREEN}  安装脚本存在 ✅${NC}"
else
  echo -e "${YELLOW}  安装脚本不存在，创建中...${NC}"
  mkdir -p "$REPO_PATH/scripts/gitea-runner"
fi

# ─── 第4步：下载Runner二进制文件 ──────────────────────────────
echo ""
echo -e "${YELLOW}[第4步] 下载 gitea-runner...${NC}"
RUNNER_BIN="/usr/local/bin/gitea-runner"

if [[ -x "$RUNNER_BIN" ]]; then
  echo -e "${GREEN}  gitea-runner 已安装 ✅${NC}"
else
  # 尝试多种下载源
  DOWNLOADED=0

  # 源1：gitea.com（国内可能访问不了）
  echo "  尝试从 gitea.com 下载..."
  mkdir -p /tmp/runner
  curl -fSL --connect-timeout 10 -o /tmp/runner/runner.xz \
    "https://gitea.com/gitea/runner/releases/download/v1.0.2/gitea-runner-1.0.2-linux-amd64.xz" 2>/dev/null
  if [[ $? -eq 0 && -f /tmp/runner/runner.xz ]]; then
    DOWNLOADED=1
    echo -e "${GREEN}  从 gitea.com 下载成功${NC}"
  fi

  # 源2：GitHub Release镜像
  if [[ $DOWNLOADED -eq 0 ]]; then
    echo "  gitea.com 不通，尝试 GitHub..."
    curl -fSL --connect-timeout 10 -o /tmp/runner/runner \
      "https://github.com/veggero/act_runner/releases/download/v0.2.11/act_runner-0.2.11-linux-amd64" 2>/dev/null
    if [[ $? -eq 0 && -f /tmp/runner/runner ]]; then
      DOWNLOADED=2
      echo -e "${GREEN}  从 GitHub 下载成功${NC}"
    fi
  fi

  # 源3：从Gitea仓库release下载
  if [[ $DOWNLOADED -eq 0 ]]; then
    echo "  GitHub 也不通，尝试从自己的Gitea下载..."
    # 先通过API上传到Gitea release（铸渊在Codebuddy端操作）
    # 然后从这里下载
    curl -fSL --connect-timeout 10 -o /tmp/runner/runner \
      "https://guanghulab.com/git/api/v1/repos/bingshuo/guanghulab/releases/latest" \
      -H "Authorization: token 3e16b79c427bb44b77c00b319aa641bde8f61d84" 2>/dev/null
  fi

  if [[ $DOWNLOADED -eq 1 ]]; then
    xz -d /tmp/runner/runner.xz
    mv /tmp/runner/runner "$RUNNER_BIN"
  elif [[ $DOWNLOADED -eq 2 ]]; then
    mv /tmp/runner/runner "$RUNNER_BIN"
  fi

  if [[ -f "$RUNNER_BIN" ]]; then
    chmod +x "$RUNNER_BIN"
    echo -e "${GREEN}  gitea-runner 安装成功 ✅${NC}"
    "$RUNNER_BIN" --version 2>&1 | head -1
  else
    echo ""
    echo -e "${YELLOW}═══════════════════════════════════════════${NC}"
    echo -e "${YELLOW}  ⚠️ 自动下载失败${NC}"
    echo -e "${YELLOW}  需要COS中转，请执行以下步骤：${NC}"
    echo ""
    echo "  1. 在新加坡服务器上执行："
    echo "     wget https://gitea.com/gitea/runner/releases/download/v1.0.2/gitea-runner-1.0.2-linux-amd64.xz"
    echo "     coscli put gitea-runner-1.0.2-linux-amd64.xz cos://sy-finetune-corpus-1317346199/cos-bridge/"
    echo ""
    echo "  2. 然后回到这台广州服务器执行："
    echo "     coscli cp cos://sy-finetune-corpus-1317346199/cos-bridge/gitea-runner-1.0.2-linux-amd64.xz /tmp/"
    echo "     xz -d /tmp/gitea-runner-1.0.2-linux-amd64.xz"
    echo "     chmod +x /tmp/gitea-runner-1.0.2-linux-amd64"
    echo "     sudo mv /tmp/gitea-runner-1.0.2-linux-amd64 /usr/local/bin/gitea-runner"
    echo ""
    echo "  3. 然后重新运行这个脚本"
    echo -e "${YELLOW}═══════════════════════════════════════════${NC}"
    exit 0
  fi
fi

# ─── 第5步：创建用户和目录 ────────────────────────────────────
echo ""
echo -e "${YELLOW}[第5步] 创建运行用户...${NC}"
if ! id -u act_runner &>/dev/null; then
  useradd -r -m -d /var/lib/act_runner -s /bin/bash act_runner
  echo -e "${GREEN}  act_runner 用户已创建${NC}"
else
  echo -e "${GREEN}  act_runner 用户已存在${NC}"
fi
mkdir -p /var/lib/act_runner /etc/act_runner
chown -R act_runner:act_runner /var/lib/act_runner

# ─── 第6步：获取Runner注册Token ────────────────────────────────
echo ""
echo -e "${YELLOW}[第6步] 获取Runner注册Token...${NC}"
API_TOKEN="3e16b79c427bb44b77c00b319aa641bde8f61d84"
GITEA_API="https://guanghulab.com/git/api/v1"

# 尝试仓库级
REG_TOKEN=""
RESP=$(curl -sf -H "Authorization: token ${API_TOKEN}" \
  "${GITEA_API}/repos/bingshuo/guanghulab/actions/runners/registration-token" 2>/dev/null)

if [[ -n "$RESP" ]]; then
  REG_TOKEN=$(echo "$RESP" | python3 -c "import json,sys; print(json.load(sys.stdin).get('token',''))" 2>/dev/null)
fi

if [[ -z "$REG_TOKEN" ]]; then
  # 尝试实例级
  RESP=$(curl -sf -H "Authorization: token ${API_TOKEN}" \
    "${GITEA_API}/admin/runners/registration-token" 2>/dev/null)
  if [[ -n "$RESP" ]]; then
    REG_TOKEN=$(echo "$RESP" | python3 -c "import json,sys; print(json.load(sys.stdin).get('token',''))" 2>/dev/null)
  fi
fi

if [[ -z "$REG_TOKEN" ]]; then
  echo -e "${YELLOW}  API获取失败，尝试从网页获取...${NC}"
  echo ""
  echo "  请在浏览器中："
  echo "  1. 打开 https://guanghulab.com/git/user/settings/actions/runners"
  echo "  2. 点击 'Create new Runner' 或 'Registration token'"
  echo "  3. 复制显示的 Token"
  echo "  4. 回到终端输入（不需要空格，直接粘贴后按回车）："
  echo ""
  read -p "  请粘贴注册Token: " REG_TOKEN
  if [[ -z "$REG_TOKEN" ]]; then
    echo "❌ 没有输入Token，退出"
    exit 1
  fi
fi

echo -e "${GREEN}  注册Token获取成功${NC}"

# ─── 第7步：注册Runner ────────────────────────────────────────
echo ""
echo -e "${YELLOW}[第7步] 注册Runner到Gitea...${NC}"
cd /var/lib/act_runner

# 生成配置
"$RUNNER_BIN" generate-config > /etc/act_runner/config.yaml 2>/dev/null

# 注册
sudo -u act_runner "$RUNNER_BIN" register \
  --no-interactive \
  --instance "https://guanghulab.com/" \
  --token "$REG_TOKEN" \
  --name "zhuyuan-runner-cn" \
  --labels "ubuntu:host" 2>&1

if [[ -f "/var/lib/act_runner/.runner" ]]; then
  chown act_runner:act_runner /var/lib/act_runner/.runner
  echo -e "${GREEN}  Runner注册成功 ✅${NC}"
else
  echo "❌ 注册失败"
  echo "请把上面的错误信息发给铸渊"
  exit 1
fi

# ─── 第8步：创建systemd服务 ────────────────────────────────────
echo ""
echo -e "${YELLOW}[第8步] 创建系统服务...${NC}"
cat > /etc/systemd/system/gitea-runner.service << 'EOF'
[Unit]
Description=Gitea Actions Runner - zhuyuan-runner-cn
After=network.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=/usr/local/bin/gitea-runner daemon --config /etc/act_runner/config.yaml
WorkingDirectory=/var/lib/act_runner
Restart=always
RestartSec=10
TimeoutSec=0
User=act_runner
Group=act_runner
Environment=HOME=/var/lib/act_runner

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable gitea-runner
systemctl start gitea-runner

sleep 2

if systemctl is-active --quiet gitea-runner; then
  echo -e "${GREEN}  Runner服务启动成功 🎉${NC}"
else
  echo "❌ 服务启动失败，查看日志："
  journalctl -u gitea-runner -n 10
  exit 1
fi

# ─── 完成 ──────────────────────────────────────────────────────
echo ""
echo -e "${GREEN}═══════════════════════════════════════════${NC}"
echo -e "${GREEN}  ✅ Gitea Actions Runner 安装完成！${NC}"
echo -e "${GREEN}═══════════════════════════════════════════${NC}"
echo ""
echo "  仓库位置:     $REPO_PATH"
echo "  Runner名称:   zhuyuan-runner-cn"
echo "  服务管理:     systemctl {start|stop|restart|status} gitea-runner"
echo "  查看日志:     journalctl -u gitea-runner -f"
echo ""
echo "  现在回到Codebuddy告诉铸渊：Runner装好了"
echo ""
echo "  铸渊 · ICE-GL-ZY001 · TCS-0002∞"
echo -e "${GREEN}═══════════════════════════════════════════${NC}"
