#!/bin/bash
# =============================================================================
# AWOOOI 第二個 Runner 安裝腳本
# =============================================================================
# 用途: 在 192.168.0.110 安裝第二個 self-hosted Runner (冗餘)
#
# 前置條件:
# 1. 先到 GitHub 獲取 Runner Token:
#    https://github.com/owenhytsai/awoooi/settings/actions/runners/new
#
# 執行方式:
#    ssh 192.168.0.110
#    RUNNER_TOKEN="<your-token>" bash setup-runner-2.sh
# =============================================================================

set -e

# 配置
RUNNER_NAME="awoooi-110-2"
RUNNER_DIR="/home/wooo/actions-runner-awoooi-2"
RUNNER_URL="https://github.com/owenhytsai/awoooi"
RUNNER_LABELS="self-hosted,harbor,k8s"
RUNNER_VERSION="2.321.0"

echo "=== AWOOOI Runner 2 安裝 ==="
echo "名稱: ${RUNNER_NAME}"
echo "目錄: ${RUNNER_DIR}"
echo ""

# 檢查 Token
if [ -z "${RUNNER_TOKEN}" ]; then
    echo "❌ 錯誤: 請設定 RUNNER_TOKEN 環境變數"
    echo ""
    echo "獲取步驟:"
    echo "1. 前往 https://github.com/owenhytsai/awoooi/settings/actions/runners/new"
    echo "2. 複製 Token (以 A 開頭的字串)"
    echo "3. 執行: RUNNER_TOKEN=\"<token>\" bash $0"
    exit 1
fi

# 創建目錄
mkdir -p "${RUNNER_DIR}"
cd "${RUNNER_DIR}"

# 下載 Runner (如果不存在)
if [ ! -f "./config.sh" ]; then
    echo "📥 下載 Runner ${RUNNER_VERSION}..."
    curl -o actions-runner-linux-x64.tar.gz -L \
        "https://github.com/actions/runner/releases/download/v${RUNNER_VERSION}/actions-runner-linux-x64-${RUNNER_VERSION}.tar.gz"
    tar xzf ./actions-runner-linux-x64.tar.gz
    rm -f ./actions-runner-linux-x64.tar.gz
fi

# 配置 Runner
echo "⚙️ 配置 Runner..."
./config.sh \
    --url "${RUNNER_URL}" \
    --token "${RUNNER_TOKEN}" \
    --name "${RUNNER_NAME}" \
    --labels "${RUNNER_LABELS}" \
    --unattended \
    --replace

# 安裝為 Service
echo "🔧 安裝 systemd service..."
sudo ./svc.sh install

# 配置 Watchdog
SERVICE_NAME="actions.runner.owenhytsai-awoooi.${RUNNER_NAME}"
OVERRIDE_DIR="/etc/systemd/system/${SERVICE_NAME}.service.d"

sudo mkdir -p "${OVERRIDE_DIR}"
sudo tee "${OVERRIDE_DIR}/watchdog.conf" <<'EOF'
[Service]
WatchdogSec=300
Restart=always
RestartSec=10
StartLimitIntervalSec=3600
StartLimitBurst=5
EOF

sudo systemctl daemon-reload

# 啟動 Runner
echo "🚀 啟動 Runner..."
sudo ./svc.sh start

# 驗證
echo ""
echo "=== 驗證 ==="
sudo ./svc.sh status

echo ""
echo "✅ Runner 2 安裝完成！"
echo ""
echo "📊 目前 AWOOOI Runners:"
systemctl list-units --type=service | grep "actions.runner.owenhytsai-awoooi" || echo "無"
