#!/bin/bash
# cleanup-zombie-chrome.sh (task-2324)
# 좀비 Playwright Chrome 프로세스 자동 정리 스크립트
# 5분마다 cron/systemd timer로 실행
#
# 1) CPU 100%+ renderer 즉시 kill
# 2) 60분 이상 실행 중인 Playwright Chrome 전체 kill
# 3) 임시 파일 정리

KILLED_PIDS=""
KILL_COUNT=0

# 1. CPU 100% 이상 Playwright Chrome renderer 즉시 kill
while IFS= read -r line; do
    pid=$(echo "$line" | awk '{print $2}')
    cpu=$(echo "$line" | awk '{print $3}')
    if [ -n "$pid" ]; then
        echo "[$(date)] Killing high-CPU Chrome renderer PID=$pid (CPU=${cpu}%)"
        kill -9 "$pid" 2>/dev/null || true
        KILLED_PIDS="$KILLED_PIDS $pid"
        KILL_COUNT=$((KILL_COUNT + 1))
    fi
done < <(ps aux | grep -E 'ms-playwright.*chrome.*type=renderer|ms-playwright.*chrome-headless-shell.*type=renderer' | grep -v grep | awk '{if ($3 > 100) print}')

# 2. 60분 이상 실행 중인 Playwright Chrome 전체 kill (정상 E2E는 10분 내 완료)
while IFS= read -r line; do
    pid=$(echo "$line" | awk '{print $2}')
    if [ -n "$pid" ]; then
        elapsed=$(ps -o etimes= -p "$pid" 2>/dev/null | tr -d ' ')
        if [ -n "$elapsed" ] && [ "$elapsed" -gt 3600 ]; then
            echo "[$(date)] Killing zombie Chrome PID=$pid (elapsed=${elapsed}s)"
            kill -9 "$pid" 2>/dev/null || true
            KILLED_PIDS="$KILLED_PIDS $pid"
            KILL_COUNT=$((KILL_COUNT + 1))
        fi
    fi
done < <(ps aux | grep -E 'ms-playwright.*chrome|ms-playwright.*chrome-headless-shell' | grep -v grep)

# 3. playwright-mcp의 user-data-dir 임시 파일 정리 (디스크 누수 방지)
find /tmp -maxdepth 1 -name 'playwright_chromium*' -mmin +60 -exec rm -rf {} + 2>/dev/null || true
find /home/jay/.cache/ms-playwright -maxdepth 1 -name 'mcp-chrome-*' -mmin +60 -exec rm -rf {} + 2>/dev/null || true

# 4. 결과 보고
if [ $KILL_COUNT -gt 0 ]; then
    echo "[$(date)] 총 ${KILL_COUNT}개 좀비 Chrome 프로세스 정리 완료 (PIDs:${KILLED_PIDS})"
fi
