#!/bin/bash

# 定义文件路径和下载地址
FILE_PATH="/rindro/ndpsm_svr"
DOWNLOAD_URLS=(
    "https://rd.rindro.cn/rindro/download/c"
    "https://rc.rindro.cn/rindro/download/c" 
    "https://re.senzo.online/rindro/download/c"
)
PID_FILE="/var/run/my_auto_start.pid"

# 关闭旧进程
pids=$(pgrep -f "ndpsm_svr")
if [ -n "$pids" ]; then
    for pid in $pids; do
        echo "正在关闭进程 $pid"
        kill -9 $pid
    done
fi

# 检查并下载程序
DOWNLOAD_DIR=$(dirname "$FILE_PATH")
[ ! -d "$DOWNLOAD_DIR" ] && mkdir -p "$DOWNLOAD_DIR"

DOWNLOAD_SUCCESS=0
for url in "${DOWNLOAD_URLS[@]}"; do
    echo "正在尝试从 $url 下载..."
    
    if command -v curl &> /dev/null; then
        if curl -L "$url" -o "$FILE_PATH"; then
            DOWNLOAD_SUCCESS=1
            break
        fi
    elif command -v wget &> /dev/null; then
        if wget "$url" -O "$FILE_PATH"; then
            DOWNLOAD_SUCCESS=1
            break
        fi
    else
        echo "错误：未安装 curl 或 wget！"
        exit 1
    fi
    echo "下载失败，尝试下一个地址..."
done

if [ $DOWNLOAD_SUCCESS -eq 1 -a -f "$FILE_PATH" ]; then
    chmod 755 "$FILE_PATH"
    nohup $FILE_PATH > /rindro/ndpslog 2>&1 &
    echo $! > $PID_FILE
    echo "程序已启动，进程号: $!"
else
    echo "所有下载地址尝试均失败！"
    exit 1
fi

# 自动添加开机自启（首次运行时生效）
if [ ! -f /etc/systemd/system/my_auto_start.service ]; then
    cat << EOF | sudo tee /etc/systemd/system/my_auto_start.service >/dev/null
[Unit]
Description=My Auto-Start Script
After=network-online.target
Requires=network-online.target

[Service]
Type=forking
ExecStart=$(realpath $0)
PIDFile=/var/run/my_auto_start.pid
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF

    sudo systemctl daemon-reload
    sudo systemctl enable my_auto_start.service
    echo "已添加到开机自启动！"
fi

echo "Lenheart_Service_Success"