#!/bin/bash

print_color() {
    local c="$1"
    shift
    printf "\032[${c}m%s\033[0m\n" "$*"
}

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

manage_game_process() {
    local p="com.tencent.igce"
    local a="com.epicgames.ue4.SplashActivity"
    game_pid=$(pgrep -f "^${p}$")
    [[ -z "$game_pid" ]] && {
        print_color 32 "游戏未运行，启动中..."
        am start -n "${p}/${a}" >/dev/null 2>&1
        sleep 1.5
        game_pid=$(pgrep -f "^${p}$")
        [[ -z "$game_pid" ]] && { print_color 31 "错误：启动失败，请检查安装状态。"; exit 1; } || print_color 32 "游戏已启动。"
    } || print_color 32 "游戏已在运行。"
}

manage_files() {
    local d="/data/data/com.tencent.igce"
    local l="${d}/libGame.so"
    local i="${d}/inject"
    rm -rf "$l" "$i"
    print_color 32 "[+] 文件清理完成。"
    print_color 34 "部署文件中..."
    cp -f arm64-v8a/libGame.so "$l"
    chmod 777 "$l"
    cp -f inject "$i"
    chmod 777 "$i"
    [[ -f "$l" && "$(stat -c '%a' "$l")" == "777" && -f "$i" && "$(stat -c '%a' "$i")" == "777" ]] && 
        print_color 32 "[+] 文件部署成功！" || { print_color 31 "错误：部署失败！"; exit 1; }
}

perform_injection() {
    local d="/data/data/com.tencent.igce"
    local p="com.tencent.igce"
    print_color 33 "**************************************"
    print_color 32 "[+] 注入启动..."
    print_color 33 "**************************************"
    sleep 0.5
    echo "[+] 输出："
    "${d}/inject" -n "$p" -so "${d}/libGame.so" | while read -r line; do echo "$line"; done
    print_color 32 "[+] 注入完成。"
}

cleanup() {
    local d="/data/data/com.tencent.igce"
    rm -rf "${d}/libGame.so" "${d}/inject"
    print_color 32 "[+] 清理完毕。"
}

main() {
    local h=""
    print_color 32 
    check_root_privileges
    manage_game_process
    manage_files
    perform_injection
    cleanup
    print_color 32 "操作已完美结束。"
}

main