#!/bin/bash

mkdir -p /usr/local/bin/
curl https://git.uauu.net/coolsd/khd/raw/branch/main/newkhd04 -o /usr/local/bin/khdn

# 检查是否以 root 权限运行
if [ "$EUID" -ne 0 ]; then
    echo "请以 root 权限运行此脚本"
    exit 1
fi

# 停止正在运行的 KHDN 进程
if pgrep -f "$KHDN_PROCESS" > /dev/null; then
    echo "Stopping existing KHDN process..."
    pkill -f "$KHDN_PROCESS"
fi

# 设置变量
SERVICE_NAME="khdn"
EXECUTABLE_PATH="/usr/local/bin/khdn"
chmod +x "$EXECUTABLE_PATH"


    cat > "/etc/init.d/${SERVICE_NAME}" << 'EOL'
#!/bin/sh
### BEGIN INIT INFO
# Provides:          khdn
# Required-Start:    $network $remote_fs $syslog
# Required-Stop:     $network $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: KHDN Client Service
### END INIT INFO

# 设置变量
DAEMON="/usr/local/bin/khdn"
DAEMON_NAME="khdn"
PIDFILE="/var/run/${DAEMON_NAME}.pid"
LOGFILE="/var/log/${DAEMON_NAME}.log"
DEBUGLOG="/var/log/${DAEMON_NAME}_debug.log"

# 获取 name 环境变量
get_name_var() {
    if [ -n "$name" ]; then
        echo "$name"
    elif name=$(cat /proc/1/environ | tr '\0' '\n' | grep ^name= | cut -d= -f2); then
        echo "$name"
    else
        hostname
    fi
}

# 确保只有一个实例在运行
ensure_single_instance() {
    if [ -f "$PIDFILE" ]; then
        pid=$(cat "$PIDFILE")
        if [ -d "/proc/$pid" ]; then
            echo "$DAEMON_NAME is already running."
            return 1
        else
            rm -f "$PIDFILE"
        fi
    fi
    return 0
}

# 启动服务
do_start() {
    ensure_single_instance || return 1
    name=$(get_name_var)
    echo "Starting $DAEMON_NAME with name=$name" >> "$DEBUGLOG"
    start-stop-daemon --start --background --make-pidfile --pidfile "$PIDFILE" \
        --exec /usr/bin/env -- name="$name" "$DAEMON" >> "$LOGFILE" 2>&1
    echo "$DAEMON_NAME started with PID $(cat $PIDFILE)" >> "$DEBUGLOG"
}

# 停止服务
do_stop() {
    echo "Stopping $DAEMON_NAME" >> "$DEBUGLOG"
    start-stop-daemon --stop --pidfile "$PIDFILE" --retry 10
    rm -f "$PIDFILE"
    echo "$DAEMON_NAME stopped" >> "$DEBUGLOG"
}

# 获取服务状态
get_status() {
    if [ -f "$PIDFILE" ]; then
        pid=$(cat "$PIDFILE")
        if [ -d "/proc/$pid" ]; then
            echo "$DAEMON_NAME is running (PID: $pid)"
        else
            echo "$DAEMON_NAME is not running (stale PID file)"
        fi
    else
        echo "$DAEMON_NAME is not running"
    fi
}

case "$1" in
    start)
        do_start
        ;;
    stop)
        do_stop
        ;;
    restart)
        do_stop
        do_start
        ;;
    status)
        get_status
        ;;
    *)
        echo "Usage: /etc/init.d/$DAEMON_NAME {start|stop|restart|status}"
        exit 1
        ;;
esac

exit 0
EOL

    # 设置执行权限
    chmod +x "/etc/init.d/${SERVICE_NAME}"

    # 添加服务到启动项
    update-rc.d $SERVICE_NAME defaults

    # 启动服务
    service $SERVICE_NAME start

    echo "KHDN Client 服务已安装并启动 (使用 SysV init)"

echo "安装完成"