#!/system/bin/sh

# 权限检查
[[ "$(id -u)" != "2000" && "$(id -u)" != "0" ]] && echo "\e[31m需要ROOT或AIDL权限\e[0m" && exit 1

# 分层递进式NDK检测（兼容sh解释器）
find_ndk() {
    # 1. 检查已知开发工具路径
    Pn1="com.idragoncheats.studio"
    Pn2="com.idragoncheats.studiopro"
    Pn3="com.goxome.aidestudio"
    Fd_count=0
    Fd1=""
    Fd2=""
    Fd3=""

    # 遍历3个包名，收集有效路径（排除.bak文件）
    if [ -e "/data/user/0/${Pn1}/no_backup/ndksupport-1710240003/android-ndk-aide/ndk-build" ] && [ "$(basename "/data/user/0/${Pn1}/no_backup/ndksupport-1710240003/android-ndk-aide/ndk-build")" != "*.bak" ]; then
        Fd1="${Pn1}"
        Fd_count=$((Fd_count + 1))
    fi
    if [ -e "/data/user/0/${Pn2}/no_backup/ndksupport-1710240003/android-ndk-aide/ndk-build" ] && [ "$(basename "/data/user/0/${Pn2}/no_backup/ndksupport-1710240003/android-ndk-aide/ndk-build")" != "*.bak" ]; then
        Fd2="${Pn2}"
        Fd_count=$((Fd_count + 1))
    fi
    if [ -e "/data/user/0/${Pn3}/no_backup/ndksupport-1710240003/android-ndk-aide/ndk-build" ] && [ "$(basename "/data/user/0/${Pn3}/no_backup/ndksupport-1710240003/android-ndk-aide/ndk-build")" != "*.bak" ]; then
        Fd3="${Pn3}"
        Fd_count=$((Fd_count + 1))
    fi

    # 处理多个NDK路径选择
    if [ $Fd_count -gt 0 ]; then
        if [ $Fd_count -eq 1 ]; then
            # 唯一路径
            if [ -n "$Fd1" ]; then
                echo "/data/user/0/${Fd1}/no_backup/ndksupport-1710240003/android-ndk-aide"
                return 0
            elif [ -n "$Fd2" ]; then
                echo "/data/user/0/${Fd2}/no_backup/ndksupport-1710240003/android-ndk-aide"
                return 0
            else
                echo "/data/user/0/${Fd3}/no_backup/ndksupport-1710240003/android-ndk-aide"
                return 0
            fi
        else
            # 多个路径，让用户选择
            echo "\e[31m找到多个ndk-build，输入序号\e[0m"
            idx=1
            [ -n "$Fd1" ] && echo "\e[33m[$idx]\e[90m->\e[37m ${Fd1}\e[0m" && idx=$((idx + 1))
            [ -n "$Fd2" ] && echo "\e[33m[$idx]\e[90m->\e[37m ${Fd2}\e[0m" && idx=$((idx + 1))
            [ -n "$Fd3" ] && echo "\e[33m[$idx]\e[90m->\e[37m ${Fd3}\e[0m"
            read Input
            # 验证输入
            if [ $Input -eq 1 ] && [ -n "$Fd1" ]; then
                echo "/data/user/0/${Fd1}/no_backup/ndksupport-1710240003/android-ndk-aide"
                return 0
            elif [ $Input -eq 2 ] && [ -n "$Fd2" ]; then
                echo "/data/user/0/${Fd2}/no_backup/ndksupport-1710240003/android-ndk-aide"
                return 0
            elif [ $Input -eq 3 ] && [ -n "$Fd3" ]; then
                echo "/data/user/0/${Fd3}/no_backup/ndksupport-1710240003/android-ndk-aide"
                return 0
            else
                echo "\e[31m输入无效\e[0m" && exit 1
            fi
        fi
    fi

    # 2. 检测环境变量NDK_ROOT
    if [ -n "${NDK_ROOT:-}" ] && [ -f "$NDK_ROOT/ndk-build" ] && [ -x "$NDK_ROOT/ndk-build" ] && [ "$(basename "$NDK_ROOT/ndk-build")" != "*.bak" ]; then
        echo "$NDK_ROOT"
        return 0
    fi

    # 3. 检查系统常见路径
    path1="$HOME/Android/Sdk/ndk-bundle"
    path2="$HOME/Android/Sdk/ndk/latest"
    path3="/opt/android-ndk"
    path4="/usr/local/android-ndk"
    if [ -f "$path1/ndk-build" ] && [ -x "$path1/ndk-build" ] && [ "$(basename "$path1/ndk-build")" != "*.bak" ]; then
        echo "$path1"
        return 0
    elif [ -f "$path2/ndk-build" ] && [ -x "$path2/ndk-build" ] && [ "$(basename "$path2/ndk-build")" != "*.bak" ]; then
        echo "$path2"
        return 0
    elif [ -f "$path3/ndk-build" ] && [ -x "$path3/ndk-build" ] && [ "$(basename "$path3/ndk-build")" != "*.bak" ]; then
        echo "$path3"
        return 0
    elif [ -f "$path4/ndk-build" ] && [ -x "$path4/ndk-build" ] && [ "$(basename "$path4/ndk-build")" != "*.bak" ]; then
        echo "$path4"
        return 0
    fi

    # 4. 检测项目配置文件
    if [ -f "./local.properties" ] && [ "$(basename "./local.properties")" != "*.bak" ]; then
        ndk_path=$(grep "ndk.dir=" ./local.properties | cut -d'=' -f2 | tr -d '[:space:]')
        if [ -n "$ndk_path" ] && [ -f "$ndk_path/ndk-build" ] && [ "$(basename "$ndk_path/ndk-build")" != "*.bak" ]; then
            echo "$ndk_path"
            return 0
        fi
    fi

    # 5. 手动输入兜底
    echo "\e[31m未找到ndk-build\e[0m"
    read -p "请手动输入NDK根目录（含ndk-build的文件夹）：" user_ndk
    if [ -n "$user_ndk" ] && [ -f "$user_ndk/ndk-build" ] && [ -x "$user_ndk/ndk-build" ] && [ "$(basename "$user_ndk/ndk-build")" != "*.bak" ]; then
        echo "$user_ndk"
        return 0
    else
        echo "\e[31m输入路径无效\e[0m" && exit 1
    fi
}

# 获取NDK路径
NDK_ROOT=$(find_ndk)
echo "使用NDK路径：$NDK_ROOT"

# 定义路径
SRC_DIR="./jni"
OUTPUT_FILE="/storage/emulated/0/Phantom纯C/obj/local/arm64-v8a/Phantom纯C.sh"
TMP_EXEC_PATH="/data/local/tmp/Phantom纯C.sh"
mkdir -p "$(dirname "$OUTPUT_FILE")"

# 检查是否需要编译
need_rebuild=0
if [ ! -f "$OUTPUT_FILE" ]; then
    echo "\e[33m未检测到输出文件，需要编译\e[0m"
    need_rebuild=1
else
    # 检查是否有源文件比输出文件新（排除.bak文件）
    if find "$SRC_DIR" -type f ! -name "*.bak" -newer "$OUTPUT_FILE" | grep -q .; then
        echo "\e[33m检测到更新的源文件，需要重新编译\e[0m"
        need_rebuild=1
    else
        echo "\e[32m所有源文件未修改，无需重新编译\e[0m"
    fi
fi

# 编译流程
if [ $need_rebuild -eq 1 ]; then
    echo "\e[35m开始编译...\e[0m"
    "$NDK_ROOT/ndk-build" -j$(nproc) V=0 2>&1
    if [ $? -ne 0 ]; then
        echo "\e[31m编译失败\e[0m" && exit 1
    fi

    # 移动产物（排除.bak文件）
    rm -rf "$OUTPUT_FILE" "$TMP_EXEC_PATH"
    find ./libs -type f ! -name "*.bak" -exec mv {} "$OUTPUT_FILE" \; && chmod +x "$OUTPUT_FILE"
    if [ ! -f "$OUTPUT_FILE" ]; then
        echo "\e[31m产物移动失败\e[0m" && exit 1
    fi

    # 复制到临时目录
    cp "$OUTPUT_FILE" "$TMP_EXEC_PATH" && chmod 755 "$TMP_EXEC_PATH"
    echo "\e[32m编译完成，输出文件：$OUTPUT_FILE\e[0m"
else
    # 确保临时执行文件存在
    if [ ! -f "$TMP_EXEC_PATH" ]; then
        cp "$OUTPUT_FILE" "$TMP_EXEC_PATH" && chmod 755 "$TMP_EXEC_PATH"
        echo "\e[32m已更新临时执行文件\e[0m"
    fi
fi

# 执行程序
echo -e "\n\e[33m运行程序...\e[0m"
"$TMP_EXEC_PATH"