#!/system/bin/sh
LOCAL_VERSION="26.1.1"
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
PURPLE='\033[1;35m'
CYAN='\033[1;36m'
WHITE='\033[1;37m'
NC='\033[0m'

CONFIG_DIR="/storage/emulated/0/RUALA"
CONFIG_FILE="${CONFIG_DIR}/配置.txt"

init_config() {
    if [ ! -d "$CONFIG_DIR" ]; then
        mkdir -p "$CONFIG_DIR" 2>/dev/null
    fi
    if [ ! -f "$CONFIG_FILE" ]; then
        echo "和平加载图一键制作Root" > "$CONFIG_FILE"
        echo "自动替换0-启动游戏0" >> "$CONFIG_FILE"
    fi
}

read_config() {
    local config_line2=$(sed -n '2p' "$CONFIG_FILE" 2>/dev/null)
    AUTO_REPLACE=$(echo "$config_line2" | cut -d'-' -f1 | sed 's/自动替换//g')
    LAUNCH_GAME=$(echo "$config_line2" | cut -d'-' -f2 | sed 's/启动游戏//g')
    [ -z "$AUTO_REPLACE" ] && AUTO_REPLACE=0
    [ -z "$LAUNCH_GAME" ] && LAUNCH_GAME=0
    [ "$AUTO_REPLACE" != "0" ] && [ "$AUTO_REPLACE" != "1" ] && AUTO_REPLACE=0
    [ "$LAUNCH_GAME" != "0" ] && [ "$LAUNCH_GAME" != "1" ] && LAUNCH_GAME=0
}

save_config() {
    local config_line2="自动替换${AUTO_REPLACE}-启动游戏${LAUNCH_GAME}"
    sed -i "2c $config_line2" "$CONFIG_FILE" 2>/dev/null
}

cloud_update_check() {
    echo -e "${BLUE}\n[云更新检查] 正在验证版本...${NC}"
    QQ_COLLECTION_URL="https://sharechain.qq.com/ccc3fe0a4e50bc5c14992b8790075090?qq_aio_chat_type=2"
    local cloud_content=$(curl -s --connect-timeout 5 "$QQ_COLLECTION_URL")
    
    if [ -z "$cloud_content" ]; then
        echo -e "${YELLOW}[提示] 无法连接到云端服务器，跳过更新检查${NC}"
        sleep 1
        return
    fi
    
    local cloud_version=""
    local cloud_notice=""
    local download_link=""
    
    if echo "$cloud_content" | grep -q "\[版本号\]"; then
        cloud_version=$(echo "$cloud_content" | sed -n 's/.*\[版本号\]\(.*\)\[版本号\].*/\1/p' | head -1)
    fi
    
    if echo "$cloud_content" | grep -q "\[公告\]"; then
        cloud_notice=$(echo "$cloud_content" | sed -n 's/.*\[公告\]\(.*\)\[公告\].*/\1/p' | head -1)
    fi
    
    if echo "$cloud_content" | grep -q "\[链接\]"; then
        download_link=$(echo "$cloud_content" | sed -n 's/.*\[链接\]\(.*\)\[链接\].*/\1/p' | head -1)
    fi
    
    if [ -z "$cloud_version" ]; then
        echo -e "${YELLOW}[提示] 无法获取云端版本号${NC}"
        return
    fi
    
    local current_ver=$(echo "$LOCAL_VERSION" | tr -d '.')
    local cloud_ver=$(echo "$cloud_version" | tr -d '.')
    
    if [ "$current_ver" -lt "$cloud_ver" ]; then
        clear
        show_unified_logo
        echo -e "${RED}╔══════════════════════════════════════════╗${NC}"
        echo -e "${RED}║       !! 检测到新版本可用 !!             ║${NC}"
        echo -e "${RED}╚══════════════════════════════════════════╝${NC}"
        echo ""
        echo -e "${GREEN}当前版本: ${RED}$LOCAL_VERSION${NC}"
        echo -e "${GREEN}最新版本: ${CYAN}$cloud_version${NC}"
        echo ""
        
        if [ -n "$cloud_notice" ]; then
            echo -e "${YELLOW}════════════════ 更新公告 ════════════════${NC}"
            echo -e "${WHITE}$cloud_notice${NC}"
            echo -e "${YELLOW}══════════════════════════════════════════${NC}"
        fi
        
        echo ""
        echo -e "${RED}必须更新到最新版本才能继续使用！${NC}"
        echo ""
        
        if [ -n "$download_link" ]; then
            local new_filename="星野工具箱_${cloud_version}.sh"
            echo -e "${CYAN}正在下载更新文件...${NC}"
            
            if curl -L "$download_link" -o "$new_filename" 2>/dev/null; then
                chmod 777 "$new_filename" 2>/dev/null
                echo -e "${GREEN}✅ 更新文件下载完成${NC}"
                echo -e "${YELLOW}新文件: $new_filename${NC}"
                echo ""
                echo -e "${CYAN}正在启动新版本...${NC}"
                sleep 2
                ./"$new_filename"
                exit 0
            else
                echo -e "${RED}❌ 下载失败，请检查网络连接${NC}"
                echo -e "${YELLOW}5秒后退出...${NC}"
                sleep 5
                exit 1
            fi
        else
            echo -e "${RED}❌ 无法获取下载链接${NC}"
            echo -e "${YELLOW}请联系作者获取最新版本${NC}"
            echo -e "${YELLOW}5秒后退出...${NC}"
            sleep 5
            exit 1
        fi
    else
        echo -e "${GREEN}✅ 当前版本 $LOCAL_VERSION 已是最新${NC}"
        
        if [ -n "$cloud_notice" ]; then
            echo ""
            echo -e "${YELLOW}════════════════ 最新公告 ════════════════${NC}"
            echo -e "${WHITE}$cloud_notice${NC}"
            echo -e "${YELLOW}══════════════════════════════════════════${NC}"
        fi
        
        echo ""
        echo -e "${CYAN}按 Enter 键进入主菜单...${NC}"
        read -r
        return
    fi
}

show_unified_logo() {
    echo -e "${CYAN}██████╗ ██╗   ██╗ █████╗ ██╗      █████╗ "
    echo -e "██╔══██╗██║   ██║██╔══██╗██║     ██╔══██╗"
    echo -e "██████╔╝██║   ██║███████║██║     ███████║"
    echo -e "██╔══██╗██║   ██║██╔══██║██║     ██╔══██║"
    echo -e "██║  ██║╚██████╔╝██║  ██║███████╗██║  ██║"
    echo -e "╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝${NC}"
}

show_device_info() {
    echo -e "${YELLOW}[信息] 正在检测设备信息...${NC}"
    local model=$(getprop ro.product.model 2>/dev/null || echo "未知设备")
    local android_ver=$(getprop ro.build.version.release 2>/dev/null || echo "未知版本")
    local cpu_abi=$(getprop ro.product.cpu.abi 2>/dev/null || echo "未知架构")
    local security_patch=$(getprop ro.build.version.security_patch 2>/dev/null || echo "未知日期")
    
    local root_status="NO Root"
    [ "$(id -u)" -eq 0 ] && root_status="Root"
    
    echo -e "${GREEN}设备型号: $model"
    echo -e "Android版本: $android_ver"
    echo -e "系统架构: $cpu_abi"
    echo -e "安全补丁: $security_patch"
    echo -e "脚本权限: $root_status${NC}"
}

show_about() {
    clear
    show_unified_logo
    echo -e "\n${PURPLE}关于我们${NC}"
    echo -e "${PURPLE}工具箱名称：星野多功能工具箱${NC}"
    echo -e "${CYAN}工具箱代号：RUALA${NC}"
    echo -e "${WHITE}工具箱版本${CYAN} $LOCAL_VERSION${NC}"
    echo -e "${WHITE}快手：白子酱--光源万创"
    echo -e "抖音：PUBG星野"
    echo -e "TG项目：xingyeNB886"
    echo -e "QQ交流群：1016258437，1075670676${NC}"
    read -p "按Enter返回主菜单..."
}

settings_menu() {
    clear
    show_unified_logo
    echo -e "\n${PURPLE}========== 设置菜单 ==========${NC}"
    read_config
    local config_line1=$(sed -n '1p' "$CONFIG_FILE" 2>/dev/null)
    echo -e "${WHITE}$config_line1${NC}"
    echo -e "${WHITE}[1] 自动替换${AUTO_REPLACE}${NC}"
    echo -e "${WHITE}[2] 启动游戏${LAUNCH_GAME}${NC}"
    echo ""
    echo -e "${WHITE}[1] 修改保存设置${NC}"
    echo -e "${WHITE}[0] 返回主菜单${NC}"
    echo -n "请输入选项序号: "
    read -r setting_choice
    
    case $setting_choice in
        1)
            echo -n "请选择要修改的项目[1=自动替换/2=启动游戏]: "
            read -r item_choice
            case $item_choice in
                1)
                    echo -n "请输入自动替换值[0/1]: "
                    read -r new_replace
                    if [ "$new_replace" = "0" ] || [ "$new_replace" = "1" ]; then
                        AUTO_REPLACE="$new_replace"
                        save_config
                        echo -e "${GREEN}✅ 自动替换已修改为${new_replace}${NC}"
                    else
                        echo -e "${RED}❌ 无效值，仅支持0或1${NC}"
                    fi
                    ;;
                2)
                    echo -n "请输入启动游戏值[0/1]: "
                    read -r new_launch
                    if [ "$new_launch" = "0" ] || [ "$new_launch" = "1" ]; then
                        LAUNCH_GAME="$new_launch"
                        save_config
                        echo -e "${GREEN}✅ 启动游戏已修改为${new_launch}${NC}"
                    else
                        echo -e "${RED}❌ 无效值，仅支持0或1${NC}"
                    fi
                    ;;
                *)
                    echo -e "${RED}[错误] 无效选项${NC}"
                    ;;
            esac
            ;;
        0)
            return
            ;;
        *)
            echo -e "${RED}[错误] 无效选项${NC}"
            ;;
    esac
    sleep 1
    read -p "按Enter返回设置菜单..."
    settings_menu
}

game_launch_menu() {
    clear
    show_unified_logo
    echo -e "\n${CYAN}========== 游戏启动[ROOT] ==========${NC}"
    if [ "$(id -u)" -eq 0 ]; then
        echo -e "${GREEN}[ROOT状态] 已获取ROOT权限${NC}"
    else
        echo -e "${RED}[ROOT状态] NO ROOT${NC}"
    fi
    echo -e "\n${WHITE}[1] ${GREEN}和平精英"
    echo -e "${WHITE}[0] ${RED}返回主菜单${NC}"
    echo -n "请输入选项序号: "
    read -r launch_choice
    case $launch_choice in
        1)
            echo -e "${YELLOW}正在启动和平精英...${NC}"
            am start -n com.tencent.tmgp.pubgmhd/com.epicgames.ue4.GameActivity 2>/dev/null
            [ $? -eq 0 ] && echo -e "${GREEN}✅ 和平精英启动指令已发送${NC}" || echo -e "${RED}❌ 启动失败${NC}"
            ;;
        0)
            return
            ;;
        *)
            echo -e "${RED}[错误] 无效选项${NC}"
            sleep 1
            game_launch_menu
            ;;
    esac
    read -p "按Enter返回主菜单..."
}

real_progress_bar() {
    local current=$1
    local total=$2
    local bar_length=20
    local progress=$((current * bar_length / total))
    local empty=$((bar_length - progress))
    echo -ne "${CYAN}进度: ["
    printf "%0.s█" $(seq 1 $progress)
    printf "%0.s " $(seq 1 $empty)
    echo -ne "]$(($current*100/$total))%%\r${NC}"
}

parse_range() {
    local input="$1"
    local result=()
    for part in $input; do
        if [[ "$part" =~ ^[0-9]+-[0-9]+$ ]]; then
            start=$(echo "$part" | cut -d'-' -f1)
            end=$(echo "$part" | cut -d'-' -f2)
            for ((i=start; i<=end; i++)); do
                result+=("$i")
            done
        else
            result+=("$part")
        fi
    done
    echo "$(echo "${result[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' ')"
}

get_file_size() {
    local file="$1"
    local size=$(ls -lh "$file" | awk '{print $5}')
    echo "$size"
}

convert_size_to_bytes() {
    local size="$1"
    local num=$(echo "$size" | sed 's/[^0-9.]//g')
    local unit=$(echo "$size" | sed 's/[0-9.]//g' | tr '[:lower:]' '[:upper:]')
    case $unit in
        K) num=$(echo "$num * 1024" | bc) ;;
        M) num=$(echo "$num * 1024 * 1024" | bc) ;;
        G) num=$(echo "$num * 1024 * 1024 * 1024" | bc) ;;
    esac
    echo "$num"
}

convert_bytes_to_human() {
    local bytes="$1"
    if (( $(echo "$bytes >= 1024*1024*1024" | bc -l) )); then
        echo "$(echo "scale=1; $bytes / (1024*1024*1024)" | bc)G"
    elif (( $(echo "$bytes >= 1024*1024" | bc -l) )); then
        echo "$(echo "scale=1; $bytes / (1024*1024)" | bc)M"
    elif (( $(echo "$bytes >= 1024" | bc -l) )); then
        echo "$(echo "scale=1; $bytes / 1024" | bc)K"
    else
        echo "${bytes}B"
    fi
}

calculate_gen_info() {
    local src_files=("$@")
    local total_src=${#src_files[@]}
    local per_file=$((TOTAL_TARGET / total_src))
    local remain=$((TOTAL_TARGET % total_src))
    local total_bytes=0
    local purple="\033[38;2;150;0;255m"
    local green="\033[38;2;0;255;0m"
    local cyan="\033[38;2;100;255;255m"
    local reset="\033[0m"
    echo -e "\n\033[36m[文件信息]${NC}"
    for ((i=0; i<total_src; i++)); do
        local file="${src_files[$i]}"
        local size=$(get_file_size "$file")
        local size_num=$(echo "$size" | sed 's/[^0-9.]//g')
        local size_unit=$(echo "$size" | sed 's/[0-9.]//g')
        local gen_count=$per_file
        [ $i -lt $remain ] && gen_count=$((gen_count + 1))
        local size_bytes=$(convert_size_to_bytes "$size")
        local req_bytes=$(echo "$size_bytes * $gen_count" | bc)
        local req_human=$(convert_bytes_to_human "$req_bytes")
        total_bytes=$(echo "$total_bytes + $req_bytes" | bc)
        if [ $remain -gt 0 ] && [ $i -eq $((total_src - 1)) ]; then
            echo -e "文件大小：${purple}$size_num${reset}$size_unit  将会生成${green}$gen_count${reset}个文件，需要内存${cyan}$req_human${reset}"
            echo -e "剩余${green}$remain${reset}个文件，随机选择"
        else
            echo -e "文件大小：${purple}$size_num${reset}$size_unit  将会生成${green}$gen_count${reset}个文件，需要内存${cyan}$req_human${reset}"
        fi
    done
    local total_human=$(convert_bytes_to_human "$total_bytes")
    echo -e "\n总计需要内存${cyan}$total_human${reset}"
    echo -n "是否继续？继续回车："
    read -r confirm
}

check_root() {
    if [ "$(id -u)" -eq 0 ]; then
        echo -e "${GREEN}[状态] 已获取ROOT权限${NC}"
    else
        echo -e "${RED}[状态] NO ROOT${NC}"
    fi
}

filter_img_files() {
    local files=("$@")
    local filtered=()
    for file in "${files[@]}"; do
        filtered+=("$file")
    done
    filtered=($(echo "${filtered[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' '))
    echo "${filtered[@]}"
}

get_gradient_color() {
    local index=$1
    local total=$2
    local r=$((255 - (255 * index / total)))
    local g=128
    local b=$((255 * index / total))
    echo -ne "\033[38;2;${r};${g};${b}m"
}

show_files_with_smooth_gradient() {
    local files=("$@")
    local total=${#files[@]}
    echo -e "\n${GREEN}[搜索结果] 共搜索到${total}个有效文件${NC}"
    for ((i=0; i<total; i++)); do
        local seq_num=$((i+1))
        local color=$(get_gradient_color $i $total)
        local reset="\033[0m"
        echo -e "${color}[${seq_num}] ${files[$i]}${reset}"
    done
    export SEARCHED_FILES=("${files[@]}")
}

select_files() {
    local prompt="$1"
    local -n selected_arr=$2
    local count=${#SEARCHED_FILES[@]}
    echo -n "$prompt"
    read -r input
    [ -z "$input" ] && input="1"
    local nums=($(parse_range "$input"))
    for num in "${nums[@]}"; do
        if ! [[ "$num" =~ ^[0-9]+$ ]] || [ "$num" -lt 1 ] || [ "$num" -gt "$count" ]; then
            echo -e "${RED}[提示] 序号$num无效${NC}"
            continue
        fi
        local file="${SEARCHED_FILES[$((num-1))]}"
        selected_arr+=("$file")
        echo -e "${GREEN}[选中] $file${NC}"
    done
    [ ${#selected_arr[@]} -eq 0 ] && { echo -e "${RED}[错误] 未选中任何文件${NC}"; return 1; }
    calculate_gen_info "${selected_arr[@]}"
    return 0
}

precision_search() {
    local keyword="$1"
    local files=()
    local keywords=($(parse_range "$keyword"))
    for kw in "${keywords[@]}"; do
        while IFS= read -r file; do
            [ -f "$file" ] && files+=("$file")
        done < <(find "$SCRIPT_DIR" -type f -name "$kw" ! -path "${OUTPUT_FOLDER}/*" 2>/dev/null)
    done
    files=($(filter_img_files "${files[@]}"))
    echo "${files[@]}"
}

fuzzy_search() {
    local keyword="$1"
    local files=()
    local keywords=($(parse_range "$keyword"))
    for kw in "${keywords[@]}"; do
        while IFS= read -r file; do
            [ -f "$file" ] && files+=("$file")
        done < <(find "$SCRIPT_DIR" -type f -name "*${kw}*" ! -path "${OUTPUT_FOLDER}/*" 2>/dev/null)
    done
    files=($(filter_img_files "${files[@]}"))
    echo "${files[@]}"
}

specify_path() {
    local input="$1"
    local files=()
    local paths=($input)
    for path in "${paths[@]}"; do
        [[ ! "$path" =~ ^/ ]] && path="${SCRIPT_DIR}/${path}"
        local parsed_paths=($(parse_range "$path"))
        for p in "${parsed_paths[@]}"; do
            local real_p=$(readlink -f "$p" 2>/dev/null || echo "$p")
            [ -f "$real_p" ] && files+=("$real_p") || echo -e "${RED}[提示] 路径$p无效${NC}"
        done
    done
    files=($(filter_img_files "${files[@]}"))
    echo "${files[@]}"
}

generate_loading_imgs() {
    local src_files=("$@")
    local total_src=${#src_files[@]}
    local per_file=$((TOTAL_TARGET / total_src))
    local remain=$((TOTAL_TARGET % total_src))
    mkdir -p "$OUTPUT_FOLDER" && rm -rf "${OUTPUT_FOLDER}"/*
    echo -e "\n${CYAN}[生成任务] 开始生成${TOTAL_TARGET}个加载图...${NC}"
    local success=0
    local idx=0
    real_progress_bar 0 $TOTAL_TARGET
    for ((i=0; i<total_src; i++)); do
        local src="${src_files[$i]}"
        local gen_count=$per_file
        [ $i -lt $remain ] && gen_count=$((gen_count+1))
        for ((j=0; j<gen_count; j++)); do
            [ $idx -ge $TOTAL_TARGET ] && break
            local target="${OUTPUT_FOLDER}/${TARGET_ALL[$idx]}"
            cp -f "$src" "$target" 2>/dev/null && success=$((success+1))
            idx=$((idx+1))
            real_progress_bar $idx $TOTAL_TARGET
        done
    done
    real_progress_bar $TOTAL_TARGET $TOTAL_TARGET
    echo -e "\n${GREEN}[生成完成] 成功${success}个 | 失败$((TOTAL_TARGET-success))个${NC}"
    echo -e "${CYAN}[输出目录] $OUTPUT_FOLDER${NC}"
}

auto_replace() {
    read_config
    echo -e "${YELLOW}[自动执行] 读取保存的设置...${NC}"
    echo -e "自动替换: ${AUTO_REPLACE} | 启动游戏: ${LAUNCH_GAME}"
    
    if [ "$AUTO_REPLACE" = "1" ]; then
        mkdir -p "$LOADINGBG_FOLDER" && rm -rf "${LOADINGBG_FOLDER}"/*
        cp -f "${OUTPUT_FOLDER}"/* "$LOADINGBG_FOLDER"/ 2>/dev/null && echo -e "${GREEN}✅ 替换成功${NC}" || echo -e "${RED}❌ 替换失败${NC}"
    else
        echo -e "${YELLOW}ℹ️  已跳过替换（配置为自动替换0）${NC}"
    fi
    
    if [ "$LAUNCH_GAME" = "1" ]; then
        echo -e "${CYAN}正在启动和平精英...${NC}"
        am start -n com.tencent.tmgp.pubgmhd/com.epicgames.ue4.GameActivity 2>/dev/null
        [ $? -eq 0 ] && echo -e "${GREEN}✅ 启动指令已发送${NC}" || echo -e "${RED}❌ 启动失败${NC}"
    else
        echo -e "${YELLOW}ℹ️  已跳过启动游戏（配置为启动游戏0）${NC}"
    fi
}

ask_and_save_config() {
    echo -e -n "${YELLOW}是否替换游戏内文件[0/1]：${NC}"
    read -r replace_choice
    while [ "$replace_choice" != "0" ] && [ "$replace_choice" != "1" ]; do
        echo -e "${RED}无效选择！${NC}"
        echo -e -n "${YELLOW}请输入0或1：${NC}"
        read -r replace_choice
    done
    
    echo -e -n "${YELLOW}是否启动游戏[0/1]：${NC}"
    read -r launch_choice
    while [ "$launch_choice" != "0" ] && [ "$launch_choice" != "1" ]; do
        echo -e "${RED}无效选择！${NC}"
        echo -e -n "${YELLOW}请输入0或1：${NC}"
        read -r launch_choice
    done
    
    AUTO_REPLACE="$replace_choice"
    LAUNCH_GAME="$launch_choice"
    save_config
    echo -e "${GREEN}✅ 设置已保存，下次将自动执行${NC}"
}

loading_img_maker() {
    SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
    OUTPUT_FOLDER="${SCRIPT_DIR}/加载图输出"
    LOADINGBG_FOLDER="/storage/emulated/0/Android/data/com.tencent.tmgp.pubgmhd/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/ImageDownloadV3/LoadingBG"
    TOTAL_TARGET=61
    TARGET_ALL=("139f7ca4602884c210afd4193459d03b" "33b643f557f43d5b254340100d981d10" "350eef5300f19b90cb99babf6d97b038" "6800fb237e5eb16cd726bb9201b07051" "6f1f2da5655591f3e414f9cb2f637364" "8450181c81be27e448abc8b2eb24b49b" "9bb41bcd562fb5e08f8efbf064957d60" "d1f95cf4b3f8990d8b0444575a1fbb61" "dc9de740a5e4939f041c7c33fe6e5abd" "2b3ee26822e44e9ee5fae90181d534d3" "33d6d44faa806c43197c2a92aabc7460" "59f95ac8c3555e4af9ef92cd881f0612" "6e0156c739f31797a89122c009afb3fb" "711e059443369ce055b46dc56f9cf40a" "864f05443816f3c3f9aa9b0fdceb7f38" "a26516845498fc100bbc825b7b68af7c" "bdb5cb02a2256317c81129c65d9e417b" "de97370724f88a85edd5866d2c3182c3" "ffc29f7b097133e8f3d39ee61269cb91" "1307d8cb164b1716150b1193661d419e" "43c0dd62e8ff2873ab30390dfff69bec" "453adf21a45ebd52f922bae31adfb2ce" "68db71d6258d3baed1064cb9d26dabe8" "712a425e67ea455e5c0e1a010f2beed2" "8aefdd285ef0b319c6c654cebe042c00" "984c5a0871c77b4be3f35e50b5562169" "a7cda6b5093f2ed4432a65fdfc1e3ae8" "df257341f217aa7c08d73cc0f0c1ee6d" "fc97d5aec6ecb8150a455e5c0e1a010f2beed2" "fdbf63af94954971ad1fea90533664d8" "08c12c2475fff37179438cc4f325f08f" "28c4eae03701eb484686d5b1d4f9c0e8" "368d5e16e8498530a455e5c0e1a010f2beed2" "52a710e8c12b81f03f91b32a49e4b587" "685aacc44cfa18a28d38c4a07cbc1c9a" "7319d40ff352f0f743fb0337253366c3" "90c97b7b097133e8f3d39ee61269cb91" "a978a939e073614558b000d814a847a2" "e28867b2c4fd1f02db9d61427d8284ab" "3d0669e39a72cbcaffbf11e15e62c4ce" "461f2f063269ccd64880179ae909bd37" "4e014cdb4f6c86fb58fb53f03bf4a51b" "75a9e7dc45a1a4923e414cdb4f6c86fb" "8f399605f7eaefc627b4ad657686403d" "919bfd8d9c899b8ccbeec86f25435864" "ae33b94972013f4dcaf978c9f2df79c5" "eb0529ed435d48cada1e8ccd524688a4" "0ba735da8cdf5051002edf4e081f4dac" "15af1123e6120451c93ddd34eb6f9568" "252418a57d99663ca1e3a88b74e583e7" "77fe6105888e1c96f2cae3eae8394140" "987c58e6d4ce229193e7c8664ef66ad9" "a67bcfa3f48e06d8f37206b57fbf85f9" "b91ada8a1edb5fc4351f6943e23f95d1" "e56bcefea38cb6bae624bbeedbef6a01" "ed7decac5bd9bf7f527508b4e52d95d2" "7e2deab32ce95d434b42639c74fdba12" "9a1a58aaf8002720b19a4cc5cecf2873" "b99fb15b059585b2e437ff5b3690a676" "fc85adec013f896f21544c549fb35960" "059b9b9068b8d0d806a5e134fff970ce")
    rm -rf "${OUTPUT_FOLDER}"/*
    clear
    show_unified_logo
    echo -e "\n${CYAN}==================== 和平加载图制作工具 ====================${NC}"
    check_root
    echo -e "${YELLOW}加载图输出文件夹内文件已删除${NC}"
    echo -e "\n${WHITE}请选择文件获取方式${NC}"
    echo -e "${RED}[1] 精准搜索"
    echo -e "${BLUE}[2] 模糊搜索"
    echo -e "${GREEN}[3] 指定路径${NC}"
    echo -n "输入选项序号："
    read -r mode
    local files=()
    case $mode in
        1)
            echo -n "输入精准搜索关键词："
            read -r kw
            files=($(precision_search "$kw"))
            ;;
        2)
            echo -n "输入模糊搜索关键词："
            read -r kw
            files=($(fuzzy_search "$kw"))
            ;;
        3)
            echo -n "输入文件路径："
            read -r path
            files=($(specify_path "$path"))
            ;;
        *)
            echo -e "${RED}[错误] 无效选项${NC}"
            read -p "按Enter返回主菜单..."
            return
            ;;
    esac
    [ ${#files[@]} -eq 0 ] && {
        echo -e "${RED}[错误] 未找到有效文件${NC}"
        read -p "按Enter返回主菜单..."
        return
    }
    show_files_with_smooth_gradient "${files[@]}"
    local selected_files=()
    while ! select_files "输入选择序号：" selected_files; do
        echo "请重新输入"
    done
    generate_loading_imgs "${selected_files[@]}"
    
    if [ "$(id -u)" -eq 0 ]; then
        if [ -f "$CONFIG_FILE" ] && grep -q "自动替换" "$CONFIG_FILE" && grep -q "启动游戏" "$CONFIG_FILE"; then
            auto_replace
        else
            ask_and_save_config
            auto_replace
        fi
    fi
    
    echo -e "\n${CYAN}[替换指引] NO ROOT手动替换步骤${NC}"
    echo -e "1 打开MT管理器，进入${OUTPUT_FOLDER}"
    echo -e "2 全选文件，复制到${LOADINGBG_FOLDER}"
    echo -e "3 覆盖原有文件完成替换"
    read -p "按Enter返回主菜单..."
}

show_main_menu() {
    clear
    show_unified_logo
    echo -e "\n${CYAN}星野多功能工具箱 v$LOCAL_VERSION${NC}"
    show_device_info
    echo -e "\n${PURPLE}功能模块选择${NC}"
    echo -e "${WHITE}[1] ${GREEN}和平加载图一键制作"
    echo -e "${WHITE}[2] ${BLUE}游戏启动[ROOT]"
    echo -e "${WHITE}[3] ${PURPLE}关于我们"
    echo -e "${WHITE}[4] ${CYAN}设置"
    echo -e "${WHITE}[0] ${RED}退出脚本${NC}"
    echo -n "请输入选项序号："
    read -r func_choice
    # 修复：输入为空时不设为0，保持为空让后续判断为无效选项
    return $func_choice
}

main() {
    clear
    show_unified_logo
    init_config
    cloud_update_check
    
    while true; do
        show_main_menu
        local func_choice=$?
        case $func_choice in
            1) loading_img_maker ;;
            2) game_launch_menu ;;
            3) show_about ;;
            4) settings_menu ;;
            0)
                echo -e "${GREEN}感谢使用，再见！${NC}"
                exit 0
                ;;
            *)
                echo -e "${RED}[错误] 无效选项${NC}"
                sleep 1
                ;;
        esac
    done
}

main
exit 0
