#!/bin/bash
# =============================================================================
# Runner Diagnostic Cleanup Script
# =============================================================================
# 解決 _diag/pages 檔案衝突問題
#
# 部署位置: 192.168.0.110 (awoooi-runner)
# 執行方式: systemd timer 每 5 分鐘執行
#
# 版本: v1.0
# 建立: 2026-03-29 (台北時區)
# 建立者: Claude Code (Runner 穩定性修復)
# =============================================================================

set -euo pipefail

RUNNER_DIR="/home/wooo/actions-runner-awoooi"
DIAG_PAGES_DIR="${RUNNER_DIR}/_diag/pages"
LOG_FILE="/var/log/runner-diag-cleanup.log"
MAX_AGE_MINUTES=10

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# 只有當 Runner 不在執行 Job 時才清理
check_runner_idle() {
    # 檢查是否有正在執行的 Job
    if pgrep -f "Runner.Worker" > /dev/null 2>&1; then
        return 1  # Runner 忙碌中
    fi
    return 0  # Runner 閒置
}

cleanup_diag_pages() {
    if [[ ! -d "$DIAG_PAGES_DIR" ]]; then
        log "DIAG_PAGES_DIR not found, skipping"
        return 0
    fi

    # 統計檔案數量
    local count=$(find "$DIAG_PAGES_DIR" -type f -name "*.log" 2>/dev/null | wc -l)

    if [[ $count -eq 0 ]]; then
        return 0
    fi

    log "Found $count diagnostic files"

    # 刪除超過 MAX_AGE_MINUTES 的檔案
    local deleted=$(find "$DIAG_PAGES_DIR" -type f -name "*.log" -mmin +${MAX_AGE_MINUTES} -delete -print 2>/dev/null | wc -l)

    if [[ $deleted -gt 0 ]]; then
        log "Deleted $deleted stale files (older than ${MAX_AGE_MINUTES}m)"
    fi
}

cleanup_work_temp() {
    # 清理 _work/_temp 目錄中的殘留檔案
    local temp_dir="${RUNNER_DIR}/_work/_temp"
    if [[ -d "$temp_dir" ]]; then
        local deleted=$(find "$temp_dir" -type f -mmin +30 -delete -print 2>/dev/null | wc -l)
        if [[ $deleted -gt 0 ]]; then
            log "Deleted $deleted temp files from _work/_temp"
        fi
    fi
}

main() {
    # 檢查 Runner 是否閒置
    if ! check_runner_idle; then
        log "Runner is busy, skipping cleanup"
        exit 0
    fi

    cleanup_diag_pages
    cleanup_work_temp

    log "Cleanup completed"
}

main "$@"
