#!/usr/bin/env bash
# ════════════════════════════════════════════════════════════════
# 光湖 · Gitea Actions 启用脚本
# 解决：not_found: /api/actions/ping.v1.PingService/Ping
# 原因：Gitea 1.23.7 默认未启用 Actions，需修改 app.ini
# ════════════════════════════════════════════════════════════════

set +e

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

echo -e "${CYAN}═══════════════════════════════════════════${NC}"
echo -e "${CYAN}  光湖 · 启用 Gitea Actions${NC}"
echo -e "${CYAN}═══════════════════════════════════════════${NC}"
echo ""

# ─── 第1步：找到Gitea的运行方式 ────────────────────────────────
echo -e "${YELLOW}[第1步] 检查Gitea运行方式...${NC}"

# 检查Docker容器
echo "  检查Docker容器..."
ALL_CONTAINERS=$(docker ps -a --format "{{.Names}} {{.Image}} {{.Ports}}" 2>/dev/null)
echo "$ALL_CONTAINERS"
echo ""

# 检查Gitea进程
echo "  检查Gitea进程..."
GITEA_PROC=$(ps aux | grep -i gitea | grep -v grep)
echo "$GITEA_PROC"
echo ""

# 检查systemd服务
echo "  检查systemd服务..."
systemctl list-units --type=service | grep -i gitea 2>/dev/null || echo "  没有gitea systemd服务"
echo ""

# ─── 第2步：找到app.ini ──────────────────────────────────────
echo -e "${YELLOW}[第2步] 查找Gitea配置文件 app.ini...${NC}"

APP_INI=""

# 常见位置
for p in \
  "/etc/gitea/app.ini" \
  "/data/gitea/conf/app.ini" \
  "/var/lib/gitea/custom/conf/app.ini" \
  "/opt/gitea/custom/conf/app.ini" \
  "/home/git/gitea/custom/conf/app.ini" \
  "/app/gitea/custom/conf/app.ini"
do
  if [[ -f "$p" ]]; then
    APP_INI="$p"
    echo -e "${GREEN}  找到了！${APP_INI}${NC}"
    break
  fi
done

# 没找到，全局搜索
if [[ -z "$APP_INI" ]]; then
  echo "  常见位置没找到，搜索中（可能需要1-2分钟）..."
  FOUND=$(find / -name "app.ini" -path "*/gitea/*" -o -name "app.ini" -path "*/custom/*" 2>/dev/null | head -5)
  if [[ -n "$FOUND" ]]; then
    echo "  搜索结果:"
    echo "$FOUND"
    # 取第一个
    APP_INI=$(echo "$FOUND" | head -1)
    echo -e "${GREEN}  使用: ${APP_INI}${NC}"
  fi
fi

# 检查Docker容器内的app.ini
if [[ -z "$APP_INI" ]]; then
  echo "  宿主机没找到，检查Docker容器内..."
  for container in $(docker ps --format "{{.Names}}" 2>/dev/null); do
    CONTAINER_INI=$(docker exec "$container" find / -name "app.ini" -path "*/gitea/*" 2>/dev/null | head -1)
    if [[ -n "$CONTAINER_INI" ]]; then
      echo -e "${GREEN}  在容器 ${container} 中找到: ${CONTAINER_INI}${NC}"
      echo "  容器ID: $container"
      echo "  需要用 docker exec 操作"
      DOCKER_CONTAINER="$container"
      DOCKER_APP_INI="$CONTAINER_INI"
      break
    fi
  done
fi

if [[ -z "$APP_INI" && -z "$DOCKER_CONTAINER" ]]; then
  echo -e "${RED}  ❌ 没找到 app.ini${NC}"
  echo ""
  echo "  请手动查找："
  echo "    docker ps                          # 看容器列表"
  echo "    docker exec <容器名> find / -name app.ini  # 在容器内搜索"
  echo ""
  echo "  找到后重新运行这个脚本"
  exit 1
fi

# ─── 第3步：检查当前Actions配置 ───────────────────────────────
echo ""
echo -e "${YELLOW}[第3步] 检查当前Actions配置...${NC}"

if [[ -n "$APP_INI" ]]; then
  echo "  当前 [actions] 配置:"
  grep -A5 '\[actions\]' "$APP_INI" 2>/dev/null || echo "  (没有 [actions] 段，说明从未配置)"
fi

# ─── 第4步：启用Actions ────────────────────────────────────────
echo ""
echo -e "${YELLOW}[第4步] 启用Gitea Actions...${NC}"

if [[ -n "$DOCKER_CONTAINER" ]]; then
  # Docker方式
  echo "  在Docker容器中操作..."
  docker exec "$DOCKER_CONTAINER" sh -c "
    # 检查是否已有 [actions] 段
    if grep -q '\[actions\]' '$DOCKER_APP_INI'; then
      # 修改已有配置
      sed -i 's/ENABLED = false/ENABLED = true/' '$DOCKER_APP_INI'
      # 如果没有 ENABLED 行就添加
      if ! grep -q 'ENABLED' '$DOCKER_APP_INI' | grep -A1 '\[actions\]'; then
        sed -i '/\[actions\]/a ENABLED = true' '$DOCKER_APP_INI'
      fi
    else
      # 添加新的 [actions] 段
      echo '' >> '$DOCKER_APP_INI'
      echo '[actions]' >> '$DOCKER_APP_INI'
      echo 'ENABLED = true' >> '$DOCKER_APP_INI'
    fi
  "
  echo -e "${GREEN}  配置已修改${NC}"

  # 重启Gitea容器
  echo "  重启Gitea容器..."
  docker restart "$DOCKER_CONTAINER"
  echo -e "${GREEN}  容器已重启${NC}"

elif [[ -n "$APP_INI" ]]; then
  # 宿主机方式
  # 备份
  cp "$APP_INI" "${APP_INI}.bak.$(date +%Y%m%d%H%M%S)"

  # 添加/修改配置
  if grep -q '\[actions\]' "$APP_INI"; then
    # 已有 [actions] 段
    if grep -A1 '\[actions\]' "$APP_INI" | grep -q 'ENABLED = false'; then
      sed -i 's/ENABLED = false/ENABLED = true/' "$APP_INI"
    elif ! grep -A1 '\[actions\]' "$APP_INI" | grep -q 'ENABLED'; then
      sed -i '/\[actions\]/a ENABLED = true' "$APP_INI"
    fi
  else
    # 没有 [actions] 段，追加
    echo "" >> "$APP_INI"
    echo "[actions]" >> "$APP_INI"
    echo "ENABLED = true" >> "$APP_INI"
  fi

  echo -e "${GREEN}  配置已修改${NC}"

  # 重启Gitea
  echo "  重启Gitea..."
  if systemctl is-active --quiet gitea 2>/dev/null; then
    systemctl restart gitea
    echo -e "${GREEN}  systemctl restart gitea 完成${NC}"
  elif pgrep -f "gitea web" > /dev/null; then
    # 手动运行的Gitea，需要找到进程并重启
    GITEA_PID=$(pgrep -f "gitea web")
    echo "  Gitea PID: $GITEA_PID"
    echo "  请手动重启Gitea进程"
  else
    echo -e "${YELLOW}  不确定如何重启Gitea，请手动重启${NC}"
  fi
fi

# ─── 第5步：验证 ──────────────────────────────────────────────
echo ""
echo -e "${YELLOW}[第5步] 验证Actions是否启用...${NC}"
echo "  等待Gitea启动（5秒）..."
sleep 5

ACTIONS_CHECK=$(curl -sf http://127.0.0.1:3001/api/v1/admin/runners/registration-token \
  -H "Authorization: token 3e16b79c427bb44b77c00b319aa641bde8f61d84" 2>/dev/null)

if [[ -n "$ACTIONS_CHECK" ]]; then
  echo -e "${GREEN}  Actions API 可用！✅${NC}"
  echo "  返回: $ACTIONS_CHECK"
else
  echo -e "${YELLOW}  Actions API 暂时不可用，Gitea可能还在重启中${NC}"
  echo "  请等30秒后再试："
  echo '  curl -sf http://127.0.0.1:3001/api/v1/admin/runners/registration-token -H "Authorization: token 3e16b79c427bb44b77c00b319aa641bde8f61d84"'
fi

echo ""
echo -e "${GREEN}═══════════════════════════════════════════${NC}"
echo -e "${GREEN}  配置修改完成${NC}"
echo -e "${GREEN}═══════════════════════════════════════════${NC}"
echo ""
echo "  下一步：重新注册Runner"
echo "  cd /var/lib/act_runner"
echo "  sudo -u act_runner /usr/local/bin/gitea-runner register \\"
echo "    --no-interactive \\"
echo "    --instance https://guanghulab.com/ \\"
echo "    --token <注册Token> \\"
echo "    --name zhuyuan-runner-cn \\"
echo "    --labels 'ubuntu:host'"
echo ""
echo "  或重新运行初始化脚本"
