#!/bin/sh

CLCyan="\033[36m"
CLWhite="\033[37m"
CLYellow="\033[33m"
CLGreen="\033[32m" 
GREEN="\033[32m"
RED="\033[31m"
NC="\033[0m"

log_message() {
    local message="\$1"
    local log_file='/var/log/neko_update.log'
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$timestamp] $message" >> "$log_file"
}

get_version_info() {
    local component="\$1"
    local version_file
    local latest_version
    local current_version

    case $component in
        "neko")
            version_file='/etc/neko/version_neko.txt'
            ;;
        "core")
            version_file='/etc/neko/version_mihomo.txt'
            ;;
        "ui")
            version_file='/etc/neko/ui/metacubexd/version.txt'
            ;;
        "singbox")
            version_file='/etc/neko/version_singbox.txt'
            ;;
        *)
            return 1
    esac

    if [ -e "$version_file" ] && [ -s "$version_file" ]; then
        current_version=$(cat "$version_file")
    else
        current_version="Not installed"
    fi

    if [ "$language_choice" = "cn" ]; then
        echo -e "${CYAN}Component: $component, Current version: $current_version${NC}"
    else
        echo -e "${CYAN}Component: $component, Current Version: $current_version${NC}"
    fi

    local releases_url
    case $component in
        "neko")
            releases_url="https://api.github.com/repos/Thaolga/neko/releases/latest"
            ;;
        "core")
            releases_url="https://api.github.com/repos/MetaCubeX/mihomo/releases/latest"
            ;;
        "ui")
            releases_url="https://api.github.com/repos/MetaCubeX/metacubexd/releases/latest"
            ;;
        "singbox")
            releases_url="https://api.github.com/repos/SagerNet/sing-box/releases/latest"
            ;;
    esac

    latest_version=$(curl -s "$releases_url" | grep '"tag_name":' | sed -E 's/.*"tag_name": "([^"]+)".*/\1/')

    if [ -z "$latest_version" ]; then
        if [ "$language_choice" = "cn" ]; then
            echo -e "${RED}Failed to fetch the latest version. Please check your network connection or GitHub API status.${NC}"
        else
            echo -e "${RED}Failed to get the latest version. Please check your internet connection or GitHub API status.${NC}"
        fi
        latest_version="Fetch failed"
    fi

    if [ "$language_choice" = "cn" ]; then
        echo -e "${CYAN}Latest version: $latest_version${NC}"
    else
        echo -e "${CYAN}Latest Version: $latest_version${NC}"
    fi
}

install_ipk() {
    repo_owner="Thaolga"
    repo_name="openwrt-nekobox"
    package_name="luci-app-nekobox"
    releases_url="https://api.github.com/repos/$repo_owner/$repo_name/releases/latest"

    echo -e "${CYAN}Updating opkg package list...${NC}"
    opkg update

    response=$(wget -qO- "$releases_url")
    if [ -z "$response" ]; then
        echo -e "${RED}Unable to access the GitHub releases page.${NC}"
        return 1
    fi

    asset_file_name=$(echo "$response" | grep -o "\"name\": \"${package_name}_[^\"]*_all\.ipk\"" | head -1 | cut -d'"' -f4)
    if [ -z "$asset_file_name" ]; then
        echo -e "${RED}Could not find the asset file for $package_name.${NC}"
        return 1
    fi

    new_version=$(echo "$response" | grep '"tag_name":' | sed -E 's/.*"tag_name": "([^"]+)".*/\1/')
    if [ -z "$new_version" ]; then
        echo -e "${RED}Latest version not found.${NC}"
        return 1
    fi

    download_url="https://github.com/$repo_owner/$repo_name/releases/download/$new_version/$asset_file_name"

    echo -e "${CYAN}Downloading ONLY: $package_name${NC}"
    echo -e "${CYAN}File: $asset_file_name${NC}"
    echo -e "${CYAN}URL: $download_url${NC}"

    local_file="/tmp/$asset_file_name"
    curl -L -f -o "$local_file" "$download_url"
    if [ $? -ne 0 ]; then
        echo -e "${RED}Download failed!${NC}"
        return 1
    fi

    if [ ! -s "$local_file" ]; then
        echo -e "${RED}The downloaded file is empty or does not exist.${NC}"
        return 1
    fi

    opkg install --force-reinstall "$local_file"
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}NeKoBox installation completed. File: $asset_file_name${NC}"
        file_version=$(echo "$asset_file_name" | sed -E "s/${package_name}_([^_]+)_all\.ipk/\1/")
        echo "$file_version" > /etc/neko/neko_version.txt
        echo "$file_version" > /etc/neko/version_neko.txt
        get_version_info "neko"
    else
        echo -e "${RED}NeKoBox installation failed.${NC}"
        return 1
    fi

    rm -f "$local_file"
}

install_theme() {
    echo -e "${CYAN}Installing luci-theme-spectra...${NC}"Add commentMore actions
    opkg update && opkg install wget grep sed

    LATEST_FILE=$(wget -qO- https://github.com/Thaolga/openwrt-nekobox/releases/expanded_assets/1.8.8 | grep -o 'luci-theme-spectra_[0-9A-Za-z.\-_]*_all.ipk' | head -n1)
    wget -O /tmp/"$LATEST_FILE" "https://github.com/Thaolga/openwrt-nekobox/releases/download/1.8.8/$LATEST_FILE"
    
    if opkg install --force-reinstall /tmp/"$LATEST_FILE"; then
        echo -e "${GREEN}luci-theme-spectra installed successfully.${NC}"
    else
        echo -e "${RED}Failed to install luci-theme-spectra.${NC}"
    fi
    
    rm -f /tmp/"$LATEST_FILE"
}

install_core() {
    latest_version=$(curl -s https://api.github.com/repos/MetaCubeX/mihomo/releases/latest | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')

    if [ -z "$latest_version" ]; then
        echo -e "${RED}Unable to fetch the latest core version number. Please check your network connection.${NC}"
        return 1
    fi

    current_version=''
    install_path='/usr/bin/mihomo'
    temp_file='/tmp/mihomo.gz'
    temp_extract_path='/tmp/mihomo_temp'

    if [ -e "$install_path/version.txt" ]; then
        current_version=$(cat "$install_path/version.txt" 2>/dev/null)
    fi

    case "$(uname -m)" in
        aarch64)
            download_url="https://github.com/MetaCubeX/mihomo/releases/download/$latest_version/mihomo-linux-arm64-$latest_version.gz"
            ;;
        armv7l)
            download_url="https://github.com/MetaCubeX/mihomo/releases/download/$latest_version/mihomo-linux-armv7l-$latest_version.gz"
            ;;
        x86_64)
            download_url="https://github.com/MetaCubeX/mihomo/releases/download/$latest_version/mihomo-linux-amd64-$latest_version.gz"
            ;;
        *)
            echo -e "${RED}No suitable download link found for architecture: $(uname -m)${NC}"
            return 1
            ;;
    esac

    echo -e "${CYAN}Latest version: $latest_version${NC}"
    echo -e "${CYAN}Download link: $download_url${NC}"

    if [ "$current_version" = "$latest_version" ]; then
        echo -e "${GREEN}The current version is the latest version.${NC}"
        return 0
    fi

    wget -O "$temp_file" "$download_url"
    if [ $? -ne 0 ]; then
        echo -e "${RED}Download failed!${NC}"
        return 1
    fi

    mkdir -p "$temp_extract_path"
    gunzip -f -c "$temp_file" > "$temp_extract_path/mihomo"
    if [ $? -ne 0 ]; then
        echo -e "${RED}Extraction failed!${NC}"
        return 1
    fi

    mv "$temp_extract_path/mihomo" "$install_path"
    chmod 0755 "$install_path"
    if [ $? -ne 0 ]; then
        echo -e "${RED}Failed to set permissions!${NC}"
        return 1
    fi

    echo "$latest_version" > "/etc/neko/version_mihomo.txt"
    echo -e "${GREEN}Core update completed! Current version: $latest_version${NC}"

    rm -f "$temp_file"
    rm -rf "$temp_extract_path"
}

install_singbox() {
    local type=$1

    GREEN='\033[0;32m'
    RED='\033[0;31m'
    NC='\033[0m'

    if [ "$type" = "stable" ]; then
        latest_version=$(curl -s https://api.github.com/repos/SagerNet/sing-box/releases/latest | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
    else
        latest_version=$(curl -s https://api.github.com/repos/SagerNet/sing-box/releases | grep '"tag_name":' | head -n 1 | sed -E 's/.*"([^"]+)".*/\1/')
    fi

    if [ -z "$latest_version" ]; then
        echo -e "${RED}Unable to fetch the latest ${type:-prerelease} version. Please check your network connection.${NC}"
        exit 1
    fi

    local current_arch=$(uname -m)
    local base_version="${latest_version#v}"

    echo -e "${GREEN}Detected architecture: $current_arch${NC}"
    echo -e "${GREEN}Latest version: $latest_version${NC}"

    if opkg list-installed | grep -q '^sing-box'; then
        echo -e "${GREEN}Sing-box is already installed via opkg. Skipping opkg update.${NC}"
    else
        echo -e "${GREEN}No existing opkg installation found. Updating opkg package list...${NC}"
        opkg update
    fi

    if [ "$type" = "stable" ]; then
        echo -e "${GREEN}Installing stable version (IPK format)...${NC}"
    else
        echo -e "${GREEN}Installing pre-release version (IPK format)...${NC}"
    fi
    
    case "$current_arch" in
        aarch64|arm64)
            ipk_filename="sing-box_${base_version}_openwrt_aarch64_generic.ipk"
            download_url="https://github.com/SagerNet/sing-box/releases/download/$latest_version/$ipk_filename"
            ;;
        x86_64)
            ipk_filename="sing-box_${base_version}_openwrt_x86_64.ipk"
            download_url="https://github.com/SagerNet/sing-box/releases/download/$latest_version/$ipk_filename"
            ;;
        *)
            echo -e "${RED}No suitable download link found for architecture: $current_arch${NC}"
            exit 1
            ;;
    esac

    temp_ipk="/tmp/$ipk_filename"
    
    echo -e "${GREEN}Downloading IPK from: $download_url${NC}"
    wget -O "$temp_ipk" "$download_url"
    if [ $? -ne 0 ]; then
        echo -e "${RED}Download failed!${NC}"
        exit 1
    fi

    echo -e "${GREEN}Installing IPK package...${NC}"
    opkg install --force-depends --force-reinstall --force-overwrite "$temp_ipk"
    if [ $? -ne 0 ]; then
        echo -e "${RED}IPK installation failed!${NC}"
        echo -e "${GREEN}Trying alternative installation method...${NC}"
        opkg remove sing-box 2>/dev/null
        opkg install --force-depends "$temp_ipk"
        if [ $? -ne 0 ]; then
            echo -e "${RED}All installation attempts failed!${NC}"
            exit 1
        fi
    fi

    rm -f "$temp_ipk"
    
    echo -e "Update/installation completed! Version: ${GREEN}$latest_version${NC}"
}

install_puernya() {
    local install_path="/usr/bin/sing-box"  
    local temp_file="/tmp/sing-box.tar.gz"   
    local temp_dir="/tmp/singbox_temp"       

    local current_arch=$(uname -m)
    local download_url=""

    case "$current_arch" in
        aarch64)
            download_url="https://github.com/Thaolga/luci-app-nekoclash/releases/download/sing-box/sing-box-puernya-linux-armv8.tar.gz"
            ;;
        x86_64)
            download_url="https://github.com/Thaolga/luci-app-nekoclash/releases/download/sing-box/sing-box-puernya-linux-amd64.tar.gz"
            ;;
        *)
            echo "Unsupported architecture: $current_arch"
            exit 1
            ;;
    esac

    echo "Downloading puernya core from $download_url..."
    wget -O "$temp_file" "$download_url"
    if [ $? -ne 0 ]; then
        echo "Download failed!"
        exit 1
    fi

    echo "Extracting files..."
    mkdir -p "$temp_dir"
    tar -xzf "$temp_file" -C "$temp_dir"
    if [ $? -ne 0 ]; then
        echo "Extraction failed!"
        exit 1
    fi

    local extracted_file="$temp_dir/CrashCore"  
    if [ -f "$extracted_file" ]; then
        cp -f "$extracted_file" "$install_path"
        chmod 0755 "$install_path"
        echo "Update completed! Current version: $(basename "$download_url")"
    else
        echo "The extracted file 'CrashCore' does not exist."
        exit 1
    fi

    rm -f "$temp_file"
    rm -rf "$temp_dir"

    echo "Puernya core installation completed successfully."
}

download_ruleset() {
    local ruleset_url="https://github.com/Thaolga/openwrt-nekobox/releases/download/1.5.0/nekobox.zip"
    local temp_file="/tmp/nekobox.zip"
    local extract_dir="/www/nekobox"

    echo "正在下载 Sing-box 规则集..."
    wget -O "$temp_file" "$ruleset_url"
    if [ $? -ne 0 ]; then
        echo -e "${RED}下载失败！${NC}"
        exit 1
    fi

    echo "正在解压规则集到 $extract_dir..."
    mkdir -p "$extract_dir"
    unzip -o "$temp_file" -d "$extract_dir"
    if [ $? -ne 0 ]; then
        echo -e "${RED}解压失败！${NC}"
        exit 1
    fi

    echo "规则集下载和解压完成！"
    rm -f "$temp_file"
}

install_ui() {
    GREEN='\033[0;32m'
    RED='\033[0;31m'
    NC='\033[0m'
    CYAN='\033[0;36m'

    local install_path='/etc/neko/ui/metacubexd'
    local temp_file='/tmp/metacubexd.tgz'
    local temp_extract_path='/tmp/metacubexd_temp'

    latest_version=$(curl -s https://api.github.com/repos/MetaCubeX/metacubexd/releases/latest | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
    if [ -z "$latest_version" ]; then
        echo -e "${RED}Unable to fetch the latest UI version number. Please check your network connection.${NC}"
        return 1
    fi

    local current_version=''
    if [ -e "$install_path/version.txt" ]; then
        current_version=$(cat "$install_path/version.txt" 2>/dev/null)
    fi

    if [ "$current_version" = "$latest_version" ]; then
        echo -e "${GREEN}The current version is the latest version.${NC}"
        return 0
    fi

    local download_url="https://github.com/MetaCubeX/metacubexd/releases/download/$latest_version/compressed-dist.tgz"

   echo -e "${CYAN}Latest version: $latest_version${NC}"
    echo -e "${CYAN}Download link: $download_url${NC}"

    wget -O "$temp_file" "$download_url"
    if [ $? -ne 0 ]; then
        echo -e "${RED}Download failed!${NC}"
        return 1
    fi

    mkdir -p "$temp_extract_path"
    tar -xzf "$temp_file" -C "$temp_extract_path"
    if [ $? -ne 0 ]; then
        echo -e "${RED}Extraction failed!${NC}"
        return 1
    fi

    mkdir -p "$install_path"
    cp -r "$temp_extract_path/"* "$install_path/"
    if [ $? -ne 0 ]; then
        echo -e "${RED}File copy failed!${NC}"
        return 1
    fi

    echo "$latest_version" > "$install_path/version.txt"
    echo -e "${GREEN}UI update completed! Current version: $latest_version${NC}"

    rm -f "$temp_file"
    rm -rf "$temp_extract_path"
}

install_php() {
    GREEN="\033[32m"
    RED="\033[31m"
    YELLOW="\033[33m"
    RESET="\033[0m"

    ARCH=$(uname -m)

    if [ "$ARCH" == "aarch64" ]; then
        PHP_CGI_URL="https://github.com/Thaolga/neko/releases/download/core_neko/php8-cgi_8.3.10-1_aarch64_generic.ipk"
        PHP_URL="https://github.com/Thaolga/neko/releases/download/core_neko/php8_8.3.10-1_aarch64_generic.ipk"
        PHP_MOD_CURL_URL="https://github.com/Thaolga/neko/releases/download/core_neko/php8-mod-curl_8.3.10-1_aarch64_generic.ipk"
        PHP_MOD_ZIP_URL="https://github.com/Thaolga/neko/releases/download/core_neko/php8-mod-zip_8.2.21-1_aarch64_generic.ipk"
        JQ_URL="https://github.com/Thaolga/neko/releases/download/core_neko/jq_1.6-2_aarch64_generic.ipk"
        PHP_CLI_URL="https://github.com/Thaolga/neko/releases/download/core_neko/php8-cli_8.3.12-r1_aarch64_generic.ipk"
    elif [ "$ARCH" == "x86_64" ]; then
        PHP_CGI_URL="https://github.com/Thaolga/neko/releases/download/core_neko/php8-cgi_8.3.10-1_x86_64.ipk"
        PHP_URL="https://github.com/Thaolga/neko/releases/download/core_neko/php8_8.3.10-1_x86_64.ipk"
        PHP_MOD_CURL_URL="https://github.com/Thaolga/neko/releases/download/core_neko/php8-mod-curl_8.3.10-1_x86_64.ipk"
        PHP_MOD_ZIP_URL="https://github.com/Thaolga/neko/releases/download/core_neko/php8-mod-zip_8.2.21-1_x86_64.ipk"
        JQ_URL="https://github.com/Thaolga/neko/releases/download/core_neko/jq_1.6-2_x86_64.ipk"
        PHP_CLI_URL="https://github.com/Thaolga/neko/releases/download/core_neko/php8-cli_8.3.12-r1_x86_64.ipk"
    else
        echo -e "${RED}Unsupported architecture: $ARCH${RESET}"
        exit 1
    fi

    echo -e "${GREEN}Downloading and installing PHP CGI...${RESET}"
    wget "$PHP_CGI_URL" -O /tmp/php8-cgi.ipk
    if opkg install --force-reinstall --force-overwrite /tmp/php8-cgi.ipk; then
        echo -e "${GREEN}PHP CGI installed successfully.${RESET}"
    else
        echo -e "${RED}PHP CGI installation failed.${RESET}"
    fi

    echo -e "${GREEN}Downloading and installing PHP...${RESET}"
    wget "$PHP_URL" -O /tmp/php8.ipk
    if opkg install --force-reinstall --force-overwrite /tmp/php8.ipk; then
        echo -e "${GREEN}PHP installed successfully.${RESET}"
    else
        echo -e "${RED}PHP installation failed.${RESET}"
    fi

    echo -e "${GREEN}Downloading and installing PHP curl module...${RESET}"
    wget "$PHP_MOD_CURL_URL" -O /tmp/php8-mod-curl.ipk
    if opkg install --force-reinstall --force-overwrite /tmp/php8-mod-curl.ipk; then
        echo -e "${GREEN}PHP curl module installed successfully.${RESET}"
    else
        echo -e "${RED}PHP curl module installation failed.${RESET}"
    fi

    echo -e "${GREEN}Downloading and installing PHP zip module...${RESET}"
    wget "$PHP_MOD_ZIP_URL" -O /tmp/php8-mod-zip.ipk
    if opkg install --force-reinstall --force-overwrite /tmp/php8-mod-zip.ipk; then
        echo -e "${GREEN}PHP zip module installed successfully.${RESET}"
    else
        echo -e "${RED}PHP zip module installation failed.${RESET}"
    fi

    echo -e "${GREEN}Downloading and installing jq...${RESET}"
    wget "$JQ_URL" -O /tmp/jq.ipk
    if opkg install --force-reinstall --force-overwrite /tmp/jq.ipk; then
        echo -e "${GREEN}jq installed successfully.${RESET}"
    else
        echo -e "${RED}jq installation failed.${RESET}"
    fi
    
    echo -e "${GREEN}Downloading and installing PHP CLI...${RESET}"
    wget "$PHP_CLI_URL" -O /tmp/php8-cli.ipk
    if opkg install --force-reinstall --force-overwrite /tmp/php8-cli.ipk; then
        echo -e "${GREEN}PHP CLI installed successfully.${RESET}"
    else
        echo -e "${RED}PHP CLI installation failed.${RESET}"
    fi

    rm -f /tmp/php8-cgi.ipk /tmp/php8.ipk /tmp/php8-mod-curl.ipk /tmp/php8-mod-zip.ipk /tmp/php8-cli.ipk

    echo -e "${GREEN}Installation complete.${RESET}"
    echo -e "${YELLOW}Please restart the server to apply changes.${RESET}"
}

reboot_router() {
    echo -e "${CYAN}Rebooting the router...${NC}"
    reboot
}

install_core_menu() {
    local language=$1
    while true; do
        echo -e "${CLCyan}╔════════════════════════════════════════════════════════╗${NC}"
        if [ "$language" = "cn" ]; then
            echo -e "${CLCyan}║                  Sing-box / Puernya 核心安装菜单                 ║${NC}"
            echo -e "${CLCyan}╠════════════════════════════════════════════════════════╣${NC}"
            echo -e "${CLCyan}║  1. 安装 Sing-box 核心                                  ║${NC}"
            echo -e "${CLCyan}║  2. 安装 puernya 核心                                   ║${NC}"
            echo -e "${CLCyan}║  4. 返回主菜单                                         ║${NC}"
        else
            echo -e "${CLCyan}║                  Sing-box / Puernya Core Install Menu         ║${NC}"
            echo -e "${CLCyan}╠════════════════════════════════════════════════════════╣${NC}"
            echo -e "${CLCyan}║  1. Install Sing-box Core                              ║${NC}"
            echo -e "${CLCyan}║  2. Install puernya Core                               ║${NC}"
            echo -e "${CLCyan}║  4. Return to Main Menu                                ║${NC}"
        fi
        echo -e "${CLCyan}╚════════════════════════════════════════════════════════╝${NC}"

        if [ "$language" = "cn" ]; then
            read -p "请选择要安装的核心: " core_choice
        else
            read -p "Please select a core to install: " core_choice
        fi

        case $core_choice in
            1)
                while true; do
                    echo -e "${CLCyan}╔════════════════════════════════════════════════════════╗${NC}"
                    if [ "$language" = "cn" ]; then
                        echo -e "${CLCyan}║              请选择要安装的 Sing-box 版本                 ║${NC}"
                        echo -e "${CLCyan}╠════════════════════════════════════════════════════════╣${NC}"
                        echo -e "${CLCyan}║  1. 安装正式版                                        ║${NC}"
                        echo -e "${CLCyan}║  2. 安装预览版                                        ║${NC}"
                        echo -e "${CLCyan}║  3. 返回上级菜单                                      ║${NC}"
                    else
                        echo -e "${CLCyan}║              Please select the Sing-box version         ║${NC}"
                        echo -e "${CLCyan}╠════════════════════════════════════════════════════════╣${NC}"
                        echo -e "${CLCyan}║  1. Install Stable Version                            ║${NC}"
                        echo -e "${CLCyan}║  2. Install Pre-release Version                       ║${NC}"
                        echo -e "${CLCyan}║  3. Return to Previous Menu                           ║${NC}"
                    fi
                    echo -e "${CLCyan}╚════════════════════════════════════════════════════════╝${NC}"

                    if [ "$language" = "cn" ]; then
                        read -p "请输入选择: " sub_choice
                    else
                        read -p "Enter your choice: " sub_choice
                    fi

                    case $sub_choice in
                        1)
                            install_singbox stable
                            ;;
                        2)
                            install_singbox
                            ;;
                        3)
                            break
                            ;;
                        *)
                            if [ "$language" = "cn" ]; then
                                echo -e "${RED}无效选项，请重试。${NC}"
                            else
                                echo -e "${RED}Invalid option, please try again.${NC}"
                            fi
                            ;;
                    esac
                    echo ""
                done
                ;;
            2)
                install_puernya
                ;;
            3)
                download_ruleset
                ;;
            4)
                return
                ;;
            *)
                if [ "$language" = "cn" ]; then
                    echo -e "${RED}无效选项，请重试。${NC}"
                else
                    echo -e "${RED}Invalid option, please try again.${NC}"
                fi
                ;;
        esac
        echo ""
    done
}

show_menu() {
    local language=$1
    echo -e "${CLCyan}╔════════════════════════════════════════════════════════╗"
    if [ "$language" = "cn" ]; then
        printf "${RED}%-${WIDTH}s${NC}\n" "              NeKoBox 安装管理器              "
    else
        printf "${RED}%-${WIDTH}s${NC}\n" "              NeKoBox Installation Manager              "
    fi
    echo -e "${CLCyan}╠════════════════════════════════════════════════════════╣"
    ubus call system board | while read -r line; do
        case "$line" in
            *"system"*)
                processor=$(echo "$line" | awk -F'\"' '{print $4}')
                if [ "$language" = "cn" ]; then
                    printf "${CLYellow} %-${WIDTH}s${NC}\n" "处理器: $processor"
                else
                    printf "${CLYellow} %-${WIDTH}s${NC}\n" "Processor: $processor"
                fi
                ;;
            *"model"*)
                model=$(echo "$line" | awk -F'\"' '{print $4}')
                if [ "$language" = "cn" ]; then
                    printf "${CLYellow} %-${WIDTH}s${NC}\n" "设备型号: $model"
                else
                    printf "${CLYellow} %-${WIDTH}s${NC}\n" "Device Model: $model"
                fi
                ;;
            *"board_name"*)
                board_name=$(echo "$line" | awk -F'\"' '{print $4}')
                if [ "$language" = "cn" ]; then
                    printf "${CLYellow} %-${WIDTH}s${NC}\n" "设备主板: $board_name"
                else
                    printf "${CLYellow} %-${WIDTH}s${NC}\n" "Device Board: $board_name"
                fi
                ;;
        esac
    done
    echo -e "${CLCyan}╠════════════════════════════════════════════════════════╣"
    if [ "$language" = "cn" ]; then
        printf "${CLCyan}  %-54s ${NC}\n" "1. 安装 NeKoBox"
        printf "${CLCyan}  %-54s ${NC}\n" "2. 安装 luci-theme-spectra"
        printf "${CLCyan}  %-54s ${NC}\n" "3. 安装 Mihomo 核心"
        printf "${CLCyan}  %-54s ${NC}\n" "4. 安装 Sing-box 核心"
        printf "${CLCyan}  %-54s ${NC}\n" "5. 安装 UI 控制面板"
        printf "${CLCyan}  %-54s ${NC}\n" "6. 安装 PHP8 和 PHP8-CGI"
        printf "${CLCyan}  %-54s ${NC}\n" "7. 重启路由器"
        printf "${CLCyan}  %-54s ${NC}\n" "8. 切换到英文界面"
        printf "${CLCyan}  %-54s ${NC}\n" "0. 退出"
    else
        printf "${CLCyan}  %-54s ${NC}\n" "1. Install NeKoBox"
        printf "${CLCyan}  %-54s ${NC}\n" "2. Install luci-theme-spectra"
        printf "${CLCyan}  %-54s ${NC}\n" "3. Install Mihomo Core"
        printf "${CLCyan}  %-54s ${NC}\n" "4. Install Sing-box Core"
        printf "${CLCyan}  %-54s ${NC}\n" "5. Install UI Control Panel"
        printf "${CLCyan}  %-54s ${NC}\n" "6. Install PHP8 and PHP8-CGI"
        printf "${CLCyan}  %-54s ${NC}\n" "7. Reboot Router"
        printf "${CLCyan}  %-54s ${NC}\n" "8. Switch to Chinese Interface"
        printf "${CLCyan}  %-54s ${NC}\n" "0. Exit"
    fi
    echo -e "${CLCyan}╚════════════════════════════════════════════════════════╝"
}

main_menu() {
    local language=${1:-"en"}
    while true; do
        show_menu "$language"

        if [ "$language" = "cn" ]; then
            echo -e "${CLGreen}注意: 执行 1. 安装 NeKoBox 后，正常情况下无需单独安装 UI 控制面板和 PHP8，只有缺少依赖时才需要安装。${NC}"
        else
            echo -e "${CLGreen}Note: After executing 1. Install NeKoBox, you generally do not need to install UI Control Panel and PHP8, unless dependencies are missing.${NC}"
        fi

        echo -e "${CLCyan}╠════════════════════════════════════════════════════════╣"
        
        if [ "$language" = "cn" ]; then
            read -p "请输入选项并按回车: " choice
        else
            read -p "Please enter an option and press Enter: " choice
        fi
        case $choice in
            1)
                language_choice="cn"
                install_ipk
                ;;
            2)
                install_theme
                ;;
            3)
                install_core
                ;;
            4)
                install_core_menu "$language"
                ;;
            5)
                install_ui
                ;;
            6)
                install_php
                ;;
            7)
                reboot_router
                ;;
            8)
                if [ "$language" = "cn" ]; then
                    language="en"
                else
                    language="cn"
                fi
                ;;
            0)
                if [ "$language" = "cn" ]; then
                    echo -e "${GREEN}退出程序。${NC}"
                else
                    echo -e "${GREEN}Exiting program.${NC}"
                fi
                exit 0
                ;;
            *)
                if [ "$language" = "cn" ]; then
                    echo -e "${RED}无效选项，请重试。${NC}"
                else
                    echo -e "${RED}Invalid option, please try again.${NC}"
                fi
                ;;
        esac
    done
}

main_menu "en"
