#!/usr/bin/env bash
set -Eeuo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

PYTHON_BIN="${PYTHON_BIN:-python3}"
LOG_DIR="${LOG_DIR:-logs}"
PID_DIR="${PID_DIR:-run}"
STARTUP_WAIT="${STARTUP_WAIT:-5}"

P2_LOG="$LOG_DIR/p2.log"
HASHCAT_LOG="$LOG_DIR/p2_hashcat.log"
P2_PID_FILE="$PID_DIR/p2.pid"
HASHCAT_PID_FILE="$PID_DIR/p2_hashcat.pid"

# 如需改默认参数，直接在这里追加，例如：
# P2_ARGS=(--workers 4 --max-file-count 10)
# HASHCAT_ARGS=(--hash-file /home/kali/桌面/p2/75.txt --tg-notify-on-start)
P2_ARGS=()
HASHCAT_ARGS=()

mkdir -p "$LOG_DIR" "$PID_DIR"

is_running() {
    local pid_file="$1"
    [[ -s "$pid_file" ]] && kill -0 "$(cat "$pid_file")" 2>/dev/null
}

start_background() {
    local name="$1"
    local pid_file="$2"
    local log_file="$3"
    shift 3

    if is_running "$pid_file"; then
        echo "[$name] 已在运行，PID=$(cat "$pid_file")"
        return 0
    fi

    nohup "$@" >>"$log_file" 2>&1 &
    local pid="$!"
    echo "$pid" >"$pid_file"
    echo "[$name] 已启动，PID=$pid，日志=$log_file"
}

start_background "p2.py" "$P2_PID_FILE" "$P2_LOG" "$PYTHON_BIN" p2.py "${P2_ARGS[@]}"

sleep "$STARTUP_WAIT"
if ! is_running "$P2_PID_FILE"; then
    echo "[p2.py] 启动失败或已退出，请查看日志：$P2_LOG" >&2
    exit 1
fi

start_background "p2_hashcat.py" "$HASHCAT_PID_FILE" "$HASHCAT_LOG" "$PYTHON_BIN" p2_hashcat.py "${HASHCAT_ARGS[@]}"

echo
echo "两个任务都已后台启动。"
echo "查看日志：tail -f '$P2_LOG' '$HASHCAT_LOG'"
echo "停止任务：kill \$(cat '$P2_PID_FILE') \$(cat '$HASHCAT_PID_FILE')"
