#!/bin/bash
# Bolloon Daemon - 守护进程启动脚本
# 支持自动重启、日志轮转、PID 管理

set -e

APP_NAME="bolloon"
APP_DIR="$(cd "$(dirname "$0")/.." && pwd)"
PID_FILE="$HOME/.bolloon/daemon.pid"
LOG_FILE="$HOME/.bolloon/daemon.log"
MAX_RESTARTS=5
RESTART_DELAY=5

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] WARN:${NC} $1"
}

error() {
    echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] ERROR:${NC} $1"
}

# 获取 PID
get_pid() {
    if [ -f "$PID_FILE" ]; then
        cat "$PID_FILE"
    fi
}

# 检查进程是否运行
is_running() {
    local pid=$(get_pid)
    if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
        return 0
    fi
    return 1
}

# 启动守护进程
start() {
    if is_running; then
        log "Bolloon 已在运行 (PID: $(get_pid))"
        return 0
    fi

    log "启动 Bolloon 守护进程..."

    # 确保日志目录存在
    mkdir -p "$(dirname "$LOG_FILE")"

    # 启动进程
    cd "$APP_DIR"
    nohup npx tsx src/index.ts >> "$LOG_FILE" 2>&1 &
    local pid=$!

    # 保存 PID
    echo "$pid" > "$PID_FILE"
    log "Bolloon 已启动 (PID: $pid)"
    log "日志文件: $LOG_FILE"
}

# 停止守护进程
stop() {
    local pid=$(get_pid)

    if [ -z "$pid" ]; then
        warn "Bolloon 未运行"
        return 0
    fi

    log "停止 Bolloon (PID: $pid)..."

    # 发送 SIGTERM
    kill -TERM "$pid" 2>/dev/null || true

    # 等待进程退出
    local count=0
    while kill -0 "$pid" 2>/dev/null && [ $count -lt 10 ]; do
        sleep 1
        count=$((count + 1))
    done

    # 如果还在运行，强制终止
    if kill -0 "$pid" 2>/dev/null; then
        warn "进程未响应，发送 SIGKILL..."
        kill -KILL "$pid" 2>/dev/null || true
    fi

    # 清理 PID 文件
    rm -f "$PID_FILE"
    log "Bolloon 已停止"
}

# 重启守护进程
restart() {
    log "重启 Bolloon..."
    stop
    sleep 2
    start
}

# 查看状态
status() {
    if is_running; then
        log "Bolloon 运行中 (PID: $(get_pid))"
        # 显示资源使用
        local pid=$(get_pid)
        if [ -n "$pid" ]; then
            ps -p "$pid" -o %cpu,%mem,etime 2>/dev/null | tail -1 || true
        fi
    else
        warn "Bolloon 未运行"
    fi
}

# 查看日志
logs() {
    if [ -f "$LOG_FILE" ]; then
        tail -100 "$LOG_FILE"
    else
        warn "日志文件不存在: $LOG_FILE"
    fi
}

# 健康检查
health() {
    local port=${PORT:-54188}
    local response=$(curl -s -o /dev/null -w "%{http_code}" "http://localhost:$port/api/health" 2>/dev/null || echo "000")

    if [ "$response" = "200" ]; then
        log "健康检查通过"
        curl -s "http://localhost:$port/api/health" 2>/dev/null | head -5
    else
        error "健康检查失败 (HTTP $response)"
        return 1
    fi
}

# 清理日志
clean_logs() {
    if [ -f "$LOG_FILE" ]; then
        local size=$(du -h "$LOG_FILE" | cut -f1)
        log "当前日志大小: $size"
        > "$LOG_FILE"
        log "日志已清空"
    fi
}

# 显示帮助
show_help() {
    echo "Bolloon Daemon 守护进程管理脚本"
    echo ""
    echo "用法: $0 [命令]"
    echo ""
    echo "命令:"
    echo "  start    启动 Bolloon 守护进程"
    echo "  stop     停止 Bolloon 守护进程"
    echo "  restart  重启 Bolloon 守护进程"
    echo "  status   查看运行状态"
    echo "  logs     查看最近日志"
    echo "  health   健康检查"
    echo "  clean    清空日志"
    echo "  help     显示帮助"
    echo ""
}

# 主逻辑
case "${1:-help}" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    status)
        status
        ;;
    logs)
        logs
        ;;
    health)
        health
        ;;
    clean)
        clean_logs
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        error "未知命令: $1"
        show_help
        exit 1
        ;;
esac