#!/bin/bash

Color_Off='\e[0m'
BIWhite='\e[1;37m'

print_color() {
    printf "\033[1;37m%s\033[0m\n" "$*"
}

check_root_privileges() {
    if [[ "$(id -u)" -ne 0 ]]; then
        print_color "错误：请以 Root 权限执行！"
        exit 1
    fi
}

manage_game_process() {
    local p="$1"
    local a="$2"
    local game_pid=$(pgrep -f "^${p}$")
    if [[ -z "$game_pid" ]]; then
        print_color "游戏未运行，启动中..."
        am start -n "${p}/${a}"
        sleep 2
        game_pid=$(pgrep -f "^${p}$")
        if [[ -z "$game_pid" ]]; then
            print_color "错误：启动失败，请检查安装状态。"
            exit 1
        else
            print_color "游戏已启动"
        fi
    else
        print_color "游戏已在运行"
    fi
}

manage_files() {
    local d="$1"
    local l="${d}/libPUBGM.so"
    local i="${d}/Inject"
    rm -rf "$l" "$i"
    print_color "[+] 文件清理完成"
    cp -v libPUBGM.so "$l" && chmod -v 777 "$l"
    cp -v Inject "$i" && chmod -v 777 "$i"
    if [[ -f "$l" && "$(stat -c '%a' "$l")" == "777" && -f "$i" && "$(stat -c '%a' "$i")" == "777" ]]; then
        print_color "[+] 文件部署成功"
    else
        print_color "错误：部署失败！"
        exit 1
    fi
}

perform_injection() {
    local d="$1"
    local p="$2"
    print_color "[+] 开始注入过程..."
    "${d}/Inject" -n "$p" -so "${d}/libPUBGM.so"
    print_color "[+] 注入完成"
}

cleanup() {
    local d="$1"
    local l="${d}/libPUBGM.so"
    local i="${d}/Inject"
    print_color "[+] 开始清理文件..."
    rm -rf "$l" "$i"
    if [[ -f "$l" || -f "$i" ]]; then
        print_color "警告：清理后仍有残留文件，正在强制清理..."
        rm -rf "$l" "$i"
        if [[ -f "$l" || -f "$i" ]]; then
            print_color "错误：无法删除残留文件，请手动检查权限或文件状态！"
            exit 1
        else
            print_color "[+] 清理成功 无残留文件"
        fi
    else
        print_color "[+] 清理完毕 无残留文件"
    fi
}

process_game() {
    local p="$1"
    local a="$2"
    local d="$3"
    manage_game_process "$p" "$a"
    manage_files "$d"
    perform_injection "$d" "$p"
    cleanup "$d"
    exit 0 
}

main() {
    check_root_privileges
    PS3="请选择以上进程进行注入操作: "
    options=("国际服" "日韩服" "台湾服" "越南服" "EXITX,")
    select opt in "${options[@]}"; do
        case $opt in
            "国际服")
                process_game "com.tencent.ig" "com.epicgames.ue4.SplashActivity" "/data/data/com.tencent.ig"
                ;;
            "日韩服")
                process_game "com.pubg.krmobile" "com.epicgames.ue4.SplashActivity" "/data/data/com.pubg.krmobile"
                ;;
            "台湾服")
                process_game "com.rekoo.pubgm" "com.epicgames.ue4.SplashActivity" "/data/data/com.rekoo.pubgm"
                ;;
            "越南服")
                process_game "com.vng.pubgmobile" "com.epicgames.ue4.SplashActivity" "/data/data/com.vng.pubgmobile"
                ;;
            "EXITX")
                print_color "已退出程序"
                exit 0
                ;;
            *)
                print_color "无效选项，请重新选择。"
                ;;
        esac
    done
}

main