#!/bin/bash

# set -e
# set -x
scriptPath=$(cd $(dirname $0) && pwd)

# 加载配置文件
if [ -f "$scriptPath/config.sh" ]; then
    source "$scriptPath/config.sh"
else
    echo "❌ 无法找到配置文件: $scriptPath/config.sh"
    exit 1
fi

PID_FILE="checksum_daemon.pid"
LOG_FILE="checksum_daemon.log"


# 根据模式决定执行逻辑
ACTION="$1"
MODE="generate"

if [[ -z "$MODE" || -z "$ACTION" ]]; then
    echo "❌ 用法: $0 {start|stop|status}"
    exit 1
fi

stop_process() {
    echo "====================================================="
    echo "[stop $1]"
    ps aux | grep $1 | grep -v grep
    ps aux | grep $1 | grep -v grep | awk '{print $2}' | xargs kill -9 >/dev/null 2>&1
    echo "-----------------------------------------------------"
}

status_process() {
    echo "====================================================="
    echo "[status $1]"
    ps aux | grep -F $1 | grep -v grep
    echo "-----------------------------------------------------"
}

# 检查是否已经运行
is_running() {
    if [ -f "$PID_FILE" ]; then
        pid=$(cat "$PID_FILE")
        if ps -p "$pid" >/dev/null; then
            return 0
        else
            rm -f "$PID_FILE"
            return 1
        fi
    else
        return 1
    fi
}

# 启动守护进程
start() {
    is_running && {
        echo "❌ 守护进程已经在运行 (PID: $(cat $PID_FILE))"
        exit 1
    }

    echo "✅ 正在启动守护进程..."

    cd $scriptPath

    ./watchdog_checksum.sh "$MODE" >/dev/null 2>&1 &

    DAEMON_PID=$!
    echo "$DAEMON_PID" > "$PID_FILE"

    echo "🟢 守护进程已启动 (PID: $DAEMON_PID)，日志写入到 $LOG_FILE"
}

# 停止守护进程
stop() {
    stop_process "watchdog_checksum.sh"

    is_running || {
        echo "❌ 守护进程未运行"
        exit 1
    }

    pid=$(cat "$PID_FILE")
    kill "$pid" && {
        rm -f "$PID_FILE"
        echo "🛑 守护进程已停止 (PID: $pid)"
    } || {
        echo "❌ 停止失败"
        exit 1
    }
}

# 查看运行状态
status() {
    status_process "watchdog_checksum"
    is_running && {
        echo "🔵 守护进程正在运行 (PID: $(cat $PID_FILE))"
    } || {
        echo "⚫ 守护进程未运行"
    }
}

# 分发动作
case "$ACTION" in
start)
    start
    ;;
stop)
    stop
    ;;
status)
    status
    ;;
*)
    echo "⚠️ 用法: $0 {download|generate} {start|stop|status}"
    exit 1
    ;;
esac
