#!/bin/bash
# =============================================================================
# Deploy Runner Diagnostic Cleanup Service
# =============================================================================
# 在 192.168.0.110 (Runner 主機) 上執行此腳本
#
# 執行方式:
#   ssh wooo@192.168.0.110
#   bash /path/to/deploy-runner-cleanup.sh
#
# 版本: v1.0
# 建立: 2026-03-29 (台北時區)
# =============================================================================

set -euo pipefail

RUNNER_DIR="/home/wooo/actions-runner-awoooi"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "🚀 Deploying Runner Diagnostic Cleanup Service..."

# 1. 複製清理腳本
echo "📋 Copying cleanup script..."
cp "$SCRIPT_DIR/cleanup-runner-diag.sh" "$RUNNER_DIR/"
chmod +x "$RUNNER_DIR/cleanup-runner-diag.sh"

# 2. 安裝 systemd 服務
echo "📋 Installing systemd service..."
sudo cp "$SCRIPT_DIR/runner-diag-cleanup.service" /etc/systemd/system/
sudo cp "$SCRIPT_DIR/runner-diag-cleanup.timer" /etc/systemd/system/

# 3. 重載 systemd
echo "🔄 Reloading systemd..."
sudo systemctl daemon-reload

# 4. 啟用並啟動 timer
echo "⏰ Enabling cleanup timer..."
sudo systemctl enable --now runner-diag-cleanup.timer

# 5. 驗證
echo ""
echo "✅ Deployment complete!"
echo ""
echo "📊 Timer status:"
sudo systemctl status runner-diag-cleanup.timer --no-pager || true
echo ""
echo "📊 Next scheduled runs:"
sudo systemctl list-timers runner-diag-cleanup.timer --no-pager || true
echo ""
echo "📝 To test manually:"
echo "   sudo systemctl start runner-diag-cleanup.service"
echo "   journalctl -u runner-diag-cleanup.service -f"
