#!/bin/bash

red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
plain='\033[0m'

cur_dir=$(pwd)

APP_NAME="SC-PPanel-Node"
SERVICE_NAME="SC-PPanel-Node"
INSTALL_DIR="/root/SC-PPanel-Node"
CONFIG_DIR="/etc/SC-PPanel-Node"
CONFIG_FILE="${CONFIG_DIR}/config.yml"
CLI_NAME="sc-ppnode"
CLI_PATH="/usr/local/bin/${CLI_NAME}"
SCRIPT_STORE_DIR="/usr/local/lib/SC-PPanel-Node"
SCRIPT_STORE_PATH="${SCRIPT_STORE_DIR}/install.sh"
SCRIPT_DOWNLOAD_URL="https://new.9s.nz/downloads/pnode.sh"

# check root
[[ $EUID -ne 0 ]] && echo -e "${red}错误：${plain} 必须使用root用户运行此脚本！\n" && exit 1

# check os
if [[ -f /etc/redhat-release ]]; then
    release="centos"
elif cat /etc/issue | grep -Eqi "alpine"; then
    release="alpine"
elif cat /etc/issue | grep -Eqi "debian"; then
    release="debian"
elif cat /etc/issue | grep -Eqi "ubuntu"; then
    release="ubuntu"
elif cat /etc/issue | grep -Eqi "centos|red hat|redhat|rocky|alma|oracle linux"; then
    release="centos"
elif cat /proc/version | grep -Eqi "debian"; then
    release="debian"
elif cat /proc/version | grep -Eqi "ubuntu"; then
    release="ubuntu"
elif cat /proc/version | grep -Eqi "centos|red hat|redhat|rocky|alma|oracle linux"; then
    release="centos"
elif cat /proc/version | grep -Eqi "arch"; then
    release="arch"
else
    echo -e "${red}未检测到系统版本，请联系脚本作者！${plain}\n" && exit 1
fi

VERSION_ARG=""
API_HOST_ARG=""
SERVER_ID_ARG=""
SECRET_KEY_ARG=""
REFRESH_CLI_ONLY="false"

parse_args() {
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --api-host)
                API_HOST_ARG="$2"; shift 2 ;;
            --server-id)
                SERVER_ID_ARG="$2"; shift 2 ;;
            --secret-key)
                SECRET_KEY_ARG="$2"; shift 2 ;;
            --refresh-cli)
                REFRESH_CLI_ONLY="true"; shift ;;
            -h|--help)
                echo "用法: $0 [版本号] [--api-host URL] [--server-id ID] [--secret-key KEY]"
                exit 0 ;;
            --*)
                echo "未知参数: $1"; exit 1 ;;
            *)
                if [[ -z "$VERSION_ARG" ]]; then
                    VERSION_ARG="$1"; shift
                else
                    shift
                fi ;;
        esac
    done
}

arch=$(uname -m)

if [[ $arch == "x86_64" || $arch == "x64" || $arch == "amd64" ]]; then
    arch="64"
elif [[ $arch == "aarch64" || $arch == "arm64" ]]; then
    arch="arm64-v8a"
elif [[ $arch == "s390x" ]]; then
    arch="s390x"
else
    arch="64"
    echo -e "${yellow}检测架构失败，使用默认架构: ${arch}${plain}"
fi

if [ "$(getconf WORD_BIT)" != '32' ] && [ "$(getconf LONG_BIT)" != '64' ] ; then
    echo "本软件不支持 32 位系统(x86)，请使用 64 位系统(x86_64)，如果检测有误，请联系作者"
    exit 2
fi

if [[ -f /etc/os-release ]]; then
    os_version=$(awk -F'[= ."]' '/VERSION_ID/{print $3}' /etc/os-release)
fi
if [[ -z "$os_version" && -f /etc/lsb-release ]]; then
    os_version=$(awk -F'[= ."]+' '/DISTRIB_RELEASE/{print $2}' /etc/lsb-release)
fi

if [[ x"${release}" == x"centos" ]]; then
    if [[ ${os_version} -le 6 ]]; then
        echo -e "${red}请使用 CentOS 7 或更高版本的系统！${plain}\n" && exit 1
    fi
    if [[ ${os_version} -eq 7 ]]; then
        echo -e "${yellow}注意：CentOS 7 无法使用 hysteria1/2 协议！${plain}\n"
    fi
elif [[ x"${release}" == x"ubuntu" ]]; then
    if [[ ${os_version} -lt 16 ]]; then
        echo -e "${red}请使用 Ubuntu 16 或更高版本的系统！${plain}\n" && exit 1
    fi
elif [[ x"${release}" == x"debian" ]]; then
    if [[ ${os_version} -lt 8 ]]; then
        echo -e "${red}请使用 Debian 8 或更高版本的系统！${plain}\n" && exit 1
    fi
fi

install_base() {
    need_install_apt() {
        local packages=("$@")
        local missing=()
        local installed_list
        installed_list=$(dpkg-query -W -f='${Package}\n' 2>/dev/null | sort)

        for p in "${packages[@]}"; do
            if ! echo "$installed_list" | grep -q "^${p}$"; then
                missing+=("$p")
            fi
        done

        if [[ ${#missing[@]} -gt 0 ]]; then
            echo "安装缺失的包: ${missing[*]}"
            apt-get update -y >/dev/null 2>&1
            DEBIAN_FRONTEND=noninteractive apt-get install -y "${missing[@]}" >/dev/null 2>&1
        fi
    }

    need_install_yum() {
        local packages=("$@")
        local missing=()
        local installed_list
        installed_list=$(rpm -qa --qf '%{NAME}\n' 2>/dev/null | sort)

        for p in "${packages[@]}"; do
            if ! echo "$installed_list" | grep -q "^${p}$"; then
                missing+=("$p")
            fi
        done

        if [[ ${#missing[@]} -gt 0 ]]; then
            echo "安装缺失的包: ${missing[*]}"
            yum install -y "${missing[@]}" >/dev/null 2>&1
        fi
    }

    need_install_apk() {
        local packages=("$@")
        local missing=()
        local installed_list
        installed_list=$(apk info 2>/dev/null | sort)

        for p in "${packages[@]}"; do
            if ! echo "$installed_list" | grep -q "^${p}$"; then
                missing+=("$p")
            fi
        done

        if [[ ${#missing[@]} -gt 0 ]]; then
            echo "安装缺失的包: ${missing[*]}"
            apk add --no-cache "${missing[@]}" >/dev/null 2>&1
        fi
    }

    if [[ x"${release}" == x"centos" ]]; then
        if ! rpm -q epel-release >/dev/null 2>&1; then
            echo "安装 EPEL 源..."
            yum install -y epel-release >/dev/null 2>&1
        fi
        need_install_yum wget curl unzip tar cronie socat ca-certificates pv
        update-ca-trust force-enable >/dev/null 2>&1 || true
    elif [[ x"${release}" == x"alpine" ]]; then
        need_install_apk wget curl unzip tar socat ca-certificates pv
        update-ca-certificates >/dev/null 2>&1 || true
    elif [[ x"${release}" == x"debian" || x"${release}" == x"ubuntu" ]]; then
        need_install_apt wget curl unzip tar cron socat ca-certificates pv
        update-ca-certificates >/dev/null 2>&1 || true
    elif [[ x"${release}" == x"arch" ]]; then
        pacman -Sy --noconfirm >/dev/null 2>&1
        pacman -S --noconfirm --needed wget curl unzip tar cronie socat ca-certificates pv >/dev/null 2>&1
    fi
}

check_status() {
    if [[ ! -f "${INSTALL_DIR}/ppnode" ]]; then
        return 2
    fi
    if [[ x"${release}" == x"alpine" ]]; then
        if service "${SERVICE_NAME}" status >/dev/null 2>&1; then
            return 0
        else
            return 1
        fi
    else
        if systemctl is-active --quiet "${SERVICE_NAME}"; then
            return 0
        else
            return 1
        fi
    fi
}

generate_ppnode_config() {
    local api_host="$1"
    local server_id="$2"
    local secret_key="$3"

    mkdir -p "${CONFIG_DIR}" >/dev/null 2>&1
    cat > "${CONFIG_FILE}" <<EOF
Log:
  Level: warn
  Output:
  Access: none

Api:
  ApiHost: ${api_host}
  ServerID: ${server_id}
  SecretKey: ${secret_key}
  Timeout: 30
EOF

    echo -e "${green}${APP_NAME} 配置文件生成完成，正在重启服务${plain}"
    if [[ x"${release}" == x"alpine" ]]; then
        service "${SERVICE_NAME}" restart
    else
        systemctl restart "${SERVICE_NAME}"
    fi
    sleep 2
    check_status
    if [[ $? == 0 ]]; then
        echo -e "${green}${APP_NAME} 重启成功${plain}"
    else
        echo -e "${red}${APP_NAME} 可能启动失败，请使用 ${CLI_NAME} log 查看日志信息${plain}"
    fi
}

install_cli_wrapper() {
    cat > "${CLI_PATH}" <<EOF
#!/bin/bash
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
plain='\033[0m'

SERVICE_NAME="${SERVICE_NAME}"
CONFIG_FILE="${CONFIG_FILE}"
INSTALL_DIR="${INSTALL_DIR}"
CONFIG_DIR="${CONFIG_DIR}"
APP_NAME="${APP_NAME}"
CLI_NAME="${CLI_NAME}"
SCRIPT_STORE_PATH="${SCRIPT_STORE_PATH}"
SCRIPT_DOWNLOAD_URL="${SCRIPT_DOWNLOAD_URL}"

if [[ -f /etc/redhat-release ]]; then
    release="centos"
elif grep -Eqi "alpine" /etc/issue 2>/dev/null; then
    release="alpine"
elif grep -Eqi "debian" /etc/issue 2>/dev/null; then
    release="debian"
elif grep -Eqi "ubuntu" /etc/issue 2>/dev/null; then
    release="ubuntu"
elif grep -Eqi "centos|red hat|redhat|rocky|alma|oracle linux" /etc/issue 2>/dev/null; then
    release="centos"
elif grep -Eqi "debian" /proc/version 2>/dev/null; then
    release="debian"
elif grep -Eqi "ubuntu" /proc/version 2>/dev/null; then
    release="ubuntu"
elif grep -Eqi "centos|red hat|redhat|rocky|alma|oracle linux" /proc/version 2>/dev/null; then
    release="centos"
elif grep -Eqi "arch" /proc/version 2>/dev/null; then
    release="arch"
else
    release="unknown"
fi

run_service_cmd() {
    if command -v systemctl >/dev/null 2>&1; then
        systemctl "\$@"
    else
        service "\${SERVICE_NAME}" "\$1"
    fi
}

confirm() {
    local prompt="\$1"
    local default="\$2"
    local temp

    if [[ -n "\$default" ]]; then
        read -rp "\${prompt} [默认\${default}]: " temp
        [[ -z "\$temp" ]] && temp="\$default"
    else
        read -rp "\${prompt} [y/n]: " temp
    fi

    [[ "\$temp" == "y" || "\$temp" == "Y" ]]
}

detect_arch() {
    local arch
    arch=\$(uname -m)
    if [[ \$arch == "x86_64" || \$arch == "x64" || \$arch == "amd64" ]]; then
        echo "64"
    elif [[ \$arch == "aarch64" || \$arch == "arm64" ]]; then
        echo "arm64-v8a"
    elif [[ \$arch == "s390x" ]]; then
        echo "s390x"
    else
        echo "64"
    fi
}

resolve_version() {
    local version_arg="\$1"
    if [[ -n "\$version_arg" ]]; then
        echo "\$version_arg"
        return 0
    fi

    curl -Ls "https://api.github.com/repos/perfect-panel/PPanel-node/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/'
}

check_status() {
    if [[ ! -f "\${INSTALL_DIR}/ppnode" ]]; then
        return 2
    fi

    if [[ "\${release}" == "alpine" ]]; then
        service "\${SERVICE_NAME}" status >/dev/null 2>&1 && return 0
        return 1
    fi

    systemctl is-active --quiet "\${SERVICE_NAME}" && return 0
    return 1
}

check_enabled() {
    if [[ "\${release}" == "alpine" ]]; then
        rc-update show 2>/dev/null | grep -q "\${SERVICE_NAME}"
        return \$?
    fi

    systemctl is-enabled "\${SERVICE_NAME}" >/dev/null 2>&1
}

check_install() {
    check_status
    if [[ \$? == 2 ]]; then
        echo -e "\${red}请先安装 \${APP_NAME}\${plain}"
        return 1
    fi
    return 0
}

check_uninstall() {
    check_status
    if [[ \$? != 2 ]]; then
        echo -e "\${red}\${APP_NAME} 已安装，请不要重复安装\${plain}"
        return 1
    fi
    return 0
}

show_enable_status() {
    if check_enabled; then
        echo -e "是否开机自启: \${green}是\${plain}"
    else
        echo -e "是否开机自启: \${red}否\${plain}"
    fi
}

show_status() {
    check_status
    case \$? in
        0)
            echo -e "\${APP_NAME} 状态: \${green}已运行\${plain}"
            show_enable_status
            ;;
        1)
            echo -e "\${APP_NAME} 状态: \${yellow}未运行\${plain}"
            show_enable_status
            ;;
        2)
            echo -e "\${APP_NAME} 状态: \${red}未安装\${plain}"
            ;;
    esac
}

generate_config() {
    local api_host
    local server_id
    local secret_key

    mkdir -p "\${CONFIG_DIR}"
    read -rp "面板API地址[格式: https://example.com/]: " api_host
    api_host=\${api_host:-https://example.com/}
    read -rp "服务器ID: " server_id
    server_id=\${server_id:-1}
    read -rp "通讯密钥: " secret_key

    cat > "\${CONFIG_FILE}" <<CFG
Log:
  Level: warn
  Output:
  Access: none

Api:
  ApiHost: \${api_host}
  ServerID: \${server_id}
  SecretKey: \${secret_key}
  Timeout: 30
CFG

    echo -e "\${green}\${APP_NAME} 配置文件生成完成\${plain}"
    if check_install; then
        restart_instance
    fi
}

install_from_stored_script() {
    if [[ ! -f "\${SCRIPT_STORE_PATH}" ]]; then
        echo -e "\${red}未找到已保存的安装脚本，无法执行 install\${plain}"
        exit 1
    fi

    bash "\${SCRIPT_STORE_PATH}" "\$1"
}

update_instance() {
    local target_version

    if [[ ! -f "\${SCRIPT_STORE_PATH}" ]]; then
        echo -e "\${red}未找到已保存的安装脚本，无法执行 update\${plain}"
        exit 1
    fi

    if [[ -n "\$1" ]]; then
        target_version="\$1"
    else
        echo && echo -n -e "输入指定版本(默认最新版): " && read target_version
    fi

    bash "\${SCRIPT_STORE_PATH}" "\${target_version}"
}

start_instance() {
    check_status
    if [[ \$? == 0 ]]; then
        echo -e "\${green}\${APP_NAME} 已运行，无需再次启动\${plain}"
        return 0
    fi

    run_service_cmd start "\${SERVICE_NAME}"
    sleep 2
    check_status
    if [[ \$? == 0 ]]; then
        echo -e "\${green}\${APP_NAME} 启动成功，请使用 \${CLI_NAME} log 查看运行日志\${plain}"
    else
        echo -e "\${red}\${APP_NAME} 可能启动失败，请稍后使用 \${CLI_NAME} log 查看日志信息\${plain}"
    fi
}

stop_instance() {
    run_service_cmd stop "\${SERVICE_NAME}"
    sleep 2
    check_status
    if [[ \$? == 1 || \$? == 2 ]]; then
        echo -e "\${green}\${APP_NAME} 停止成功\${plain}"
    else
        echo -e "\${red}\${APP_NAME} 停止失败，请稍后查看日志信息\${plain}"
    fi
}

restart_instance() {
    run_service_cmd restart "\${SERVICE_NAME}"
    sleep 2
    check_status
    if [[ \$? == 0 ]]; then
        echo -e "\${green}\${APP_NAME} 重启成功，请使用 \${CLI_NAME} log 查看运行日志\${plain}"
    else
        echo -e "\${red}\${APP_NAME} 可能启动失败，请稍后使用 \${CLI_NAME} log 查看日志信息\${plain}"
    fi
}

config_instance() {
    echo "\${APP_NAME} 在修改配置后会自动尝试重启"
    mkdir -p "\${CONFIG_DIR}"
    \${EDITOR:-vi} "\${CONFIG_FILE}"
    sleep 2
    restart_instance
}

uninstall_instance() {
    confirm "确定要卸载 \${APP_NAME} 吗?" "n"
    if [[ \$? != 0 ]]; then
        return 0
    fi

    if [[ "\${release}" == "alpine" ]]; then
        service "\${SERVICE_NAME}" stop >/dev/null 2>&1 || true
        rc-update del "\${SERVICE_NAME}" default >/dev/null 2>&1 || true
        rm -f "/etc/init.d/\${SERVICE_NAME}"
    else
        systemctl stop "\${SERVICE_NAME}" >/dev/null 2>&1 || true
        systemctl disable "\${SERVICE_NAME}" >/dev/null 2>&1 || true
        rm -f "/etc/systemd/system/\${SERVICE_NAME}.service"
        systemctl daemon-reload >/dev/null 2>&1 || true
        systemctl reset-failed >/dev/null 2>&1 || true
    fi

    rm -rf "\${CONFIG_DIR}" "\${INSTALL_DIR}"
    echo
    echo -e "卸载成功。如需删除管理脚本，可手动执行 \${green}rm -f ${CLI_PATH}\${plain}"
    echo
}

update_shell() {
    local tmp_script
    local downloaded_script
    tmp_script=\$(mktemp)
    downloaded_script=\$(mktemp)

    mkdir -p "\$(dirname "\${SCRIPT_STORE_PATH}")"
    if ! curl -fsSL "\${SCRIPT_DOWNLOAD_URL}" -o "\${downloaded_script}"; then
        rm -f "\${tmp_script}" "\${downloaded_script}"
        echo -e "\${red}下载脚本失败，请检查此机器能否访问 \${SCRIPT_DOWNLOAD_URL}\${plain}"
        exit 1
    fi

    if ! grep -q -- '--refresh-cli' "\${downloaded_script}" || ! grep -q 'install_cli_wrapper()' "\${downloaded_script}"; then
        rm -f "\${tmp_script}" "\${downloaded_script}"
        echo -e "\${red}下载到的脚本版本过旧或不兼容，已拒绝覆盖本地管理脚本\${plain}"
        exit 1
    fi

    mv "\${downloaded_script}" "\${tmp_script}"
    mv "\${tmp_script}" "\${SCRIPT_STORE_PATH}"
    chmod +x "\${SCRIPT_STORE_PATH}"
    bash "\${SCRIPT_STORE_PATH}" --refresh-cli
}

open_ports() {
    systemctl stop firewalld.service 2>/dev/null
    systemctl disable firewalld.service 2>/dev/null
    setenforce 0 2>/dev/null
    ufw disable 2>/dev/null
    iptables -P INPUT ACCEPT 2>/dev/null
    iptables -P FORWARD ACCEPT 2>/dev/null
    iptables -P OUTPUT ACCEPT 2>/dev/null
    iptables -t nat -F 2>/dev/null
    iptables -t mangle -F 2>/dev/null
    iptables -F 2>/dev/null
    iptables -X 2>/dev/null
    netfilter-persistent save 2>/dev/null
    echo -e "\${green}放开防火墙端口成功！\${plain}"
}

show_usage() {
    echo "\${APP_NAME} 管理脚本使用方法:"
    echo "------------------------------------------"
    echo "\${CLI_NAME}              - 显示管理菜单"
    echo "\${CLI_NAME} start        - 启动 \${APP_NAME}"
    echo "\${CLI_NAME} stop         - 停止 \${APP_NAME}"
    echo "\${CLI_NAME} restart      - 重启 \${APP_NAME}"
    echo "\${CLI_NAME} status       - 查看 \${APP_NAME} 状态"
    echo "\${CLI_NAME} enable       - 设置 \${APP_NAME} 开机自启"
    echo "\${CLI_NAME} disable      - 取消 \${APP_NAME} 开机自启"
    echo "\${CLI_NAME} log          - 查看 \${APP_NAME} 日志"
    echo "\${CLI_NAME} config       - 编辑 \${CONFIG_FILE}"
    echo "\${CLI_NAME} generate     - 生成 \${APP_NAME} 配置文件"
    echo "\${CLI_NAME} update       - 更新 \${APP_NAME} 到最新版本"
    echo "\${CLI_NAME} update x.x.x - 更新 \${APP_NAME} 到指定版本"
    echo "\${CLI_NAME} install      - 安装 \${APP_NAME}"
    echo "\${CLI_NAME} uninstall    - 卸载 \${APP_NAME}"
    echo "\${CLI_NAME} version      - 查看 \${APP_NAME} 版本"
    echo "\${CLI_NAME} update_shell - 刷新 \${CLI_NAME} 管理脚本"
    echo "------------------------------------------"
}

show_menu() {
    while true; do
        echo -e "
  \${green}\${APP_NAME} 管理脚本\${plain}
  \${green}0.\${plain} 修改配置
  \${green}1.\${plain} 安装 \${APP_NAME}
  \${green}2.\${plain} 更新 \${APP_NAME}
  \${green}3.\${plain} 卸载 \${APP_NAME}
  \${green}4.\${plain} 启动 \${APP_NAME}
  \${green}5.\${plain} 停止 \${APP_NAME}
  \${green}6.\${plain} 重启 \${APP_NAME}
  \${green}7.\${plain} 查看 \${APP_NAME} 状态
  \${green}8.\${plain} 查看 \${APP_NAME} 日志
  \${green}9.\${plain} 设置 \${APP_NAME} 开机自启
  \${green}10.\${plain} 取消 \${APP_NAME} 开机自启
  \${green}11.\${plain} 查看 \${APP_NAME} 版本
  \${green}12.\${plain} 刷新 \${CLI_NAME} 管理脚本
  \${green}13.\${plain} 生成 \${APP_NAME} 配置文件
  \${green}14.\${plain} 放行 VPS 的所有网络端口
  \${green}15.\${plain} 退出脚本
"
        show_status
        echo
        read -rp "请输入选择 [0-15]: " num

        case "\${num}" in
            0) config_instance ;;
            1) check_uninstall && install_from_stored_script ;;
            2) check_install && update_instance ;;
            3) check_install && uninstall_instance ;;
            4) check_install && start_instance ;;
            5) check_install && stop_instance ;;
            6) check_install && restart_instance ;;
            7) check_install && if command -v systemctl >/dev/null 2>&1; then systemctl status "\${SERVICE_NAME}" --no-pager -l; else service "\${SERVICE_NAME}" status; fi ;;
            8) check_install && if command -v journalctl >/dev/null 2>&1; then journalctl -u "\${SERVICE_NAME}" -e --no-pager -f; else echo "当前系统未提供 journalctl，请直接查看服务输出或系统日志。"; fi ;;
            9) check_install && if command -v systemctl >/dev/null 2>&1; then systemctl enable "\${SERVICE_NAME}"; else rc-update add "\${SERVICE_NAME}" default; fi ;;
            10) check_install && if command -v systemctl >/dev/null 2>&1; then systemctl disable "\${SERVICE_NAME}"; else rc-update del "\${SERVICE_NAME}" default; fi ;;
            11) check_install && "\${INSTALL_DIR}/ppnode" version ;;
            12) update_shell; exit \$? ;;
            13) generate_config ;;
            14) open_ports ;;
            15) exit 0 ;;
            *) echo -e "\${red}请输入正确的数字 [0-15]\${plain}" ;;
        esac

        echo
        read -rp "按回车返回主菜单: " _
    done
}

case "\$1" in
    start)
        check_install && start_instance ;;
    stop)
        check_install && stop_instance ;;
    restart)
        check_install && restart_instance ;;
    status)
        check_install && if command -v systemctl >/dev/null 2>&1; then
            systemctl status "\${SERVICE_NAME}" --no-pager
        else
            service "\${SERVICE_NAME}" status
        fi ;;
    enable)
        check_install && if command -v systemctl >/dev/null 2>&1; then
            systemctl enable "\${SERVICE_NAME}"
        else
            rc-update add "\${SERVICE_NAME}" default
        fi ;;
    disable)
        check_install && if command -v systemctl >/dev/null 2>&1; then
            systemctl disable "\${SERVICE_NAME}"
        else
            rc-update del "\${SERVICE_NAME}" default
        fi ;;
    log)
        check_install && if command -v journalctl >/dev/null 2>&1; then
            journalctl -u "\${SERVICE_NAME}" -e --no-pager
        else
            echo "当前系统未提供 journalctl，请直接查看服务输出或系统日志。"
        fi ;;
    config)
        config_instance ;;
    generate)
        generate_config ;;
    update)
        check_install && update_instance "\$2" ;;
    install)
        check_uninstall && install_from_stored_script "\$2" ;;
    uninstall)
        check_install && uninstall_instance ;;
    version)
        check_install && "\${INSTALL_DIR}/ppnode" version ;;
    update_shell)
        update_shell ;;
    "")
        show_menu ;;
    *)
        show_usage ;;
esac
EOF
    chmod +x "${CLI_PATH}"
}

install_ppnode() {
    local version_param="$1"
    local url=""
    local last_version=""

    rm -rf "${INSTALL_DIR}"
    mkdir -p "${INSTALL_DIR}"
    cd "${INSTALL_DIR}" || exit 1

    if [[ -z "${version_param}" ]]; then
        last_version=$(curl -Ls "https://api.github.com/repos/perfect-panel/PPanel-node/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
        if [[ -z "${last_version}" ]]; then
            echo -e "${red}检测 PPanel-node 版本失败，可能是超出 GitHub API 限制，请稍后再试，或手动指定版本${plain}"
            exit 1
        fi
        echo -e "${green}检测到最新版本：${last_version}，开始安装...${plain}"
    else
        last_version="${version_param}"
    fi

    url="https://github.com/perfect-panel/PPanel-node/releases/download/${last_version}/ppanel-node-linux-${arch}.zip"
    curl -sL "${url}" | pv -s 30M -W -N "下载进度" > "${INSTALL_DIR}/ppanel-node-linux.zip"
    if [[ $? -ne 0 ]]; then
        echo -e "${red}下载 PPanel-node 失败，请确认版本存在且服务器可以访问 GitHub${plain}"
        exit 1
    fi

    unzip -o ppanel-node-linux.zip >/dev/null
    rm -f ppanel-node-linux.zip
    chmod +x ppnode

    mkdir -p "${CONFIG_DIR}"
    cp -f geoip.dat "${CONFIG_DIR}/"
    cp -f geosite.dat "${CONFIG_DIR}/"

    if [[ x"${release}" == x"alpine" ]]; then
        rm -f "/etc/init.d/${SERVICE_NAME}"
        cat > "/etc/init.d/${SERVICE_NAME}" <<EOF
#!/sbin/openrc-run

name="${SERVICE_NAME}"
description="${APP_NAME}"
command="${INSTALL_DIR}/ppnode"
command_args="server --config ${CONFIG_FILE}"
command_user="root"
pidfile="/run/${CLI_NAME}.pid"
command_background="yes"

depend() {
    need net
}
EOF
        chmod +x "/etc/init.d/${SERVICE_NAME}"
        rc-update add "${SERVICE_NAME}" default
    else
        rm -f "/etc/systemd/system/${SERVICE_NAME}.service"
        cat > "/etc/systemd/system/${SERVICE_NAME}.service" <<EOF
[Unit]
Description=${APP_NAME} Service
After=network.target nss-lookup.target
Wants=network.target

[Service]
User=root
Group=root
Type=simple
LimitAS=infinity
LimitRSS=infinity
LimitCORE=infinity
LimitNOFILE=999999
WorkingDirectory=${INSTALL_DIR}
ExecStart=${INSTALL_DIR}/ppnode server --config ${CONFIG_FILE}
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF
        systemctl daemon-reload
        systemctl enable "${SERVICE_NAME}" >/dev/null 2>&1
    fi

    if [[ ! -f "${CONFIG_FILE}" ]]; then
        if [[ -n "${API_HOST_ARG}" && -n "${SERVER_ID_ARG}" && -n "${SECRET_KEY_ARG}" ]]; then
            generate_ppnode_config "${API_HOST_ARG}" "${SERVER_ID_ARG}" "${SECRET_KEY_ARG}"
            first_install=false
        else
            cp -f config.yml "${CONFIG_FILE}"
            first_install=true
        fi
    else
        if [[ x"${release}" == x"alpine" ]]; then
            service "${SERVICE_NAME}" start
        else
            systemctl start "${SERVICE_NAME}"
        fi
        sleep 2
        check_status
        if [[ $? == 0 ]]; then
            echo -e "${green}${APP_NAME} 启动成功${plain}"
        else
            echo -e "${red}${APP_NAME} 可能启动失败，请使用 ${CLI_NAME} log 查看日志信息${plain}"
        fi
        first_install=false
    fi

    install_cli_wrapper
    mkdir -p "${SCRIPT_STORE_DIR}"
    if [[ -f "$0" ]]; then
        cp -f "$0" "${SCRIPT_STORE_PATH}"
        chmod +x "${SCRIPT_STORE_PATH}"
    fi

    cd "${cur_dir}" || exit 1
    rm -f install.sh

    echo "------------------------------------------"
    echo "${APP_NAME} 管理命令:"
    echo "------------------------------------------"
    echo "${CLI_NAME} start    - 启动 ${APP_NAME}"
    echo "${CLI_NAME} stop     - 停止 ${APP_NAME}"
    echo "${CLI_NAME} restart  - 重启 ${APP_NAME}"
    echo "${CLI_NAME} status   - 查看 ${APP_NAME} 状态"
    echo "${CLI_NAME} enable   - 设置 ${APP_NAME} 开机自启"
    echo "${CLI_NAME} disable  - 取消 ${APP_NAME} 开机自启"
    echo "${CLI_NAME} log      - 查看 ${APP_NAME} 日志"
    echo "${CLI_NAME} config   - 编辑 ${CONFIG_FILE}"
    echo "${CLI_NAME} generate - 生成 ${APP_NAME} 配置文件"
    echo "${CLI_NAME} update   - 更新 ${APP_NAME} 到最新版本"
    echo "${CLI_NAME} update x.x.x - 更新 ${APP_NAME} 到指定版本"
    echo "${CLI_NAME} install  - 安装 ${APP_NAME}"
    echo "${CLI_NAME} uninstall - 卸载 ${APP_NAME}"
    echo "${CLI_NAME} version  - 查看 ${APP_NAME} 版本"
    echo "${CLI_NAME} update_shell - 刷新 ${CLI_NAME} 管理脚本"
    echo "------------------------------------------"

    if [[ ${first_install} == true ]]; then
        read -rp "检测到第一次安装 ${APP_NAME}，是否自动生成 ${CONFIG_FILE}？(y/n): " if_generate
        if [[ "${if_generate}" =~ ^[Yy]$ ]]; then
            read -rp "面板API地址[格式: https://example.com/]: " api_host
            api_host=${api_host:-https://example.com/}
            read -rp "服务器ID: " server_id
            server_id=${server_id:-1}
            read -rp "通讯密钥: " secret_key
            generate_ppnode_config "${api_host}" "${server_id}" "${secret_key}"
        else
            echo -e "${green}已跳过自动生成配置。后续可手动编辑 ${CONFIG_FILE}${plain}"
        fi
    fi
}

parse_args "$@"
if [[ "${REFRESH_CLI_ONLY}" == "true" ]]; then
    install_cli_wrapper
    echo -e "${green}${CLI_NAME} 管理脚本刷新成功${plain}"
    exit 0
fi

echo -e "${green}开始安装 ${APP_NAME}${plain}"
install_base
install_ppnode "${VERSION_ARG}"

