#!/data/data/com.termux/files/usr/bin/bash

function get_storage_permission() {
    # 配置参数
    TIMEOUT=60  # 超时时间（秒）
    CHECK_DIR="./storage/shared"  # 权限检测目录

    # 检查初始权限
    echo "正在检查存储权限..."
    if [ -d "$CHECK_DIR" ]; then
        echo "已获取存储权限"
    else
        echo "未检测到存储权限，将请求权限"
        
        # 后台请求权限
        termux-setup-storage &
        start_time=$(date +%s)
        permission_granted=0

        # 循环监测权限状态直至超时（sh 语法）
        while true; do
            elapsed=$(expr $(date +%s) - $start_time)  # sh 中用 expr 计算
            if [ $elapsed -ge $TIMEOUT ]; then
                exit 1
            fi
            
            if [ -d "$CHECK_DIR" ]; then
                permission_granted=1
                break
            fi
            
            sleep 1  # 每秒检查一次
            echo "剩余等待时间：$((TIMEOUT - elapsed)) 秒"  # 简化的算术写法
        done

        if [ $permission_granted -eq 1 ]; then
            echo "存储权限已授予"
        fi
    fi
}

function chsrc_termux() {
    # 换源，北京外国语大学开源软件镜像站
    sed -i 's@^\(deb.*stable main\)$@#\1\ndeb https://mirrors.bfsu.edu.cn/termux/apt/termux-main stable main@' /data/data/com.termux/files/usr/etc/apt/sources.list
    apt update
}

function chsrc_python() {
    # pip换源
    python3 -m pip config --user set global.index-url https://mirrors.bfsu.edu.cn/pypi/web/simple
}

function install_dependencies() {
    # 安装必要工具和依赖
    apt install -y wget zip git python
}


function install_dependencies_python() {
    # python依赖安装
    pip install protobuf dataclasses_json requests
}

function install_kcptoken() {
    # 检查kcptocken是否已正确安装
    MODULE="kcptoken"
    pip list |grep -q "^kcptoken[[:space:]]"
    if [ $? -eq 0 ]; then
        echo "${MODULE}已正确安装"
    else
        echo "${MODULE}未安装"
        # 克隆并安装 kcptoken.py (包含之前添加的错误检查)
        echo "正在克隆 kcptoken.py 仓库..."
        # 源仓库https://github.com/AFNGP/kcptoken.py.git，这里防止出现连接问题故使用镜像仓库
        git clone https://gitee.com/rh666666/kcptoken.py.git
        if [ $? -ne 0 ]; then
            echo "错误：无法连接到Git仓库，请检查网络连接或仓库地址是否正确"
            exit 1
        fi
        cd kcptoken.py
        echo "正在编译 kcptoken.py，可能需要消耗较长时间，请耐心等待！"
        pip install .
        cd ..
        echo "已安装 kcptoken.py，删除源文件"
        rm ./kcptoken.py -rf
    fi
}


function download_latest_resources() {
    # 下载最新的资源文件
    echo "正在下载最新资源文件..."
    wget -O build.zip https://ppsr.adoleiiiiii.com/build.zip
    if [ $? -ne 0 ]; then
        echo "错误：无法下载最新资源文件，请检查网络连接或URL是否正确"
        exit 1
    fi
    unzip -o build.zip
    rm build.zip
}

function build_res() {
    # 检查并部署目录
    if [ -d "./build/misc" ]; then
        mkdir -p "./storage/shared/ppSR/misc/"
        cp ./build/misc/ "./storage/shared/ppSR/" -rf
        echo "资源文件部署完成"
    else
        echo "错误：build/misc 目录不存在，资源部署失败"
        exit 1
    fi
}

function only_unpack_hotfix() {
    if [ -d "./build/misc" ]; then
        echo "正在解压热更新包..."
        mkdir -p "./storage/shared/ppSR/misc/"
        cp ./build/misc/hotfix.json "./storage/shared/ppSR/misc/hotfix.json" -rf
        echo "热更新包解压完成"
    else
        echo "错误：build/misc 目录不存在，热更新解压失败"
        exit 1
    fi
}

function prepare_run() {

cat <<'EOF' >run.sh
# filepath: d:\.adoleiiiiii\ppSR_Android\run.sh
dir1="./storage/shared/ppSR/misc"
dir2="./build/misc"
for filename in "$dir1"/*; do
    basefile=$(basename "$filename")

    file1="$dir1/$basefile"
    file2="$dir2/$basefile"

    if [ "$file1" -nt "$file2" ]; then
        # file1 is newer
        cp "$file1" "$dir2/" -rf
    else
        # file2 is newer or same
        cp "$file2" "$dir1/" -rf
    fi

done
cd build
python ppsr.pyc
EOF
    chmod +x run.sh
    ln -s /data/data/com.termux/files/home/run.sh /data/data/com.termux/files/usr/bin/run > /dev/null 2>&1
    echo -e "脚本准备完成，可通过 \033[1;33mrun\033[0m 执行"
}

function install() {
    get_storage_permission
    chsrc_termux
    install_dependencies
    chsrc_python
    install_dependencies_python
    install_kcptoken
    download_latest_resources
    build_res
    prepare_run
}

function update() {
    echo "正在更新资源文件..."
    download_latest_resources
    only_unpack_hotfix
    echo "更新完成"
}

# 参数解析与主入口
if [ $# -eq 0 ]; then
    install
    exit 0
fi

if [ $# -ne 1 ]; then
    echo "用法: $0 [--install|-i|--update|-u]"
    exit 1
fi

case "$1" in
    --install|-i)
        install
        ;;
    --update|-u)
        update
        ;;
    *)
        echo "无效参数: $1"
        echo "用法: $0 [--install|-i|--update|-u]"
        exit 1
        ;;
esac

