#!/bin/bash

# Runner狀態驗證腳本

echo "=== Gitea Runner狀態驗證 ==="
echo ""

#檢查Runner二進制檔案
echo "1. 檢查Runner安裝..."
if [ -f ~/.local/bin/gitea-runner ]; then
    echo "✅ Runner已安裝：~/.local/bin/gitea-runner"
    VERSION=$(~/.local/bin/gitea-runner --version)
    echo "   版本：$VERSION"
else
    echo "❌ Runner未安裝"
fi

echo ""

#檢查Runner配置
echo "2. 檢查Runner配置..."
if [ -f /Users/accusys/markbase/.runner ]; then
    echo "✅ Runner配置已生成"
    echo "   配置檔案：/Users/accusys/markbase/.runner"
    RUNNER_ID=$(cat /Users/accusys/markbase/.runner | jq '.id')
    RUNNER_NAME=$(cat /Users/accusys/markbase/.runner | jq -r '.name')
    echo "   Runner ID：$RUNNER_ID"
    echo "   Runner名稱：$RUNNER_NAME"
else
    echo "❌ Runner配置未生成"
fi

echo ""

#檢查Gitea連接
echo "3. 檢查Gitea連接..."
RESPONSE=$(curl -sI https://gitea.momentry.ddns.net | head -1)
if echo "$RESPONSE" | grep -q "200"; then
    echo "✅ Gitea連接正常"
    echo "   地址：https://gitea.momentry.ddns.net"
else
    echo "❌ Gitea連接失敗"
fi

echo ""

#檢查必要環境
echo "4. 檢查必要環境..."
if command -v rustc &> /dev/null; then
    echo "✅ Rust已安裝：$(rustc --version)"
else
    echo "❌ Rust未安裝"
fi

if command -v SwitchAudioSource &> /dev/null; then
    echo "✅ SwitchAudioSource已安裝"
else
    echo "❌ SwitchAudioSource未安裝"
fi

echo ""

#檢查launchd服務
echo "5. 檢查launchd服務..."
SERVICE_STATUS=$(launchctl list | grep gitea)
if [ ! -z "$SERVICE_STATUS" ]; then
    echo "✅ Runner服務已啟動"
    echo "   狀態：$SERVICE_STATUS"
else
    echo "⚠️ Runner服務未啟動（前景執行請使用 start_runner.sh）"
fi

echo ""

#檢查日誌
echo "6. 檢查Runner日誌..."
if [ -f /tmp/gitea-runner.log ]; then
    echo "✅ Runner日誌存在"
    echo "   日誌檔案：/tmp/gitea-runner.log"
    echo "   最後10行："
    tail -10 /tmp/gitea-runner.log
else
    echo "⚠️ Runner日誌未生成（Runner尚未執行）"
fi

echo ""
echo "===驗證完成 ==="