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

# 1. 换源apt与pkg到清华源并更新
echo "正在更换为清华源..."

# 主源替换
sed -i 's@^\(deb.*stable main\)$@#\1\ndeb https://mirrors.tuna.tsinghua.edu.cn/termux/termux-packages-24 stable main@' $PREFIX/etc/apt/sources.list

# 检查并替换game源（如果存在）
if [ -f "$PREFIX/etc/apt/sources.list.d/game.list" ]; then
    sed -i 's@^\(deb.*games stable\)$@#\1\ndeb https://mirrors.tuna.tsinghua.edu.cn/termux/game-packages-24 games stable@' $PREFIX/etc/apt/sources.list.d/game.list
else
    echo "未找到game.list，跳过game源替换"
fi

# 检查并替换science源（如果存在）
if [ -f "$PREFIX/etc/apt/sources.list.d/science.list" ]; then
    sed -i 's@^\(deb.*science stable\)$@#\1\ndeb https://mirrors.tuna.tsinghua.edu.cn/termux/science-packages-24 science stable@' $PREFIX/etc/apt/sources.list.d/science.list
else
    echo "未找到science.list，跳过science源替换"
fi

# 更新软件包（强制保持当前配置文件）
echo "正在更新软件包..."
yes | pkg update -y && yes | pkg upgrade -y

# 2. 下载python3.8.10的预编译包
echo "正在下载Python 3.8.10..."
wget https://termux.org/pkg/python/3.8.10/python_3.8.10_aarch64.deb -O python.deb || {
    echo "下载Python失败，尝试备用源..."
    wget https://mirrors.tuna.tsinghua.edu.cn/termux/pkg/python/3.8.10/python_3.8.10_aarch64.deb -O python.deb || {
        echo "无法下载Python 3.8.10，尝试安装最新版Python"
        pkg install python -y
        exit 0
    }
}

# 3. 安装预编译包
echo "正在安装Python 3.8.10..."
dpkg -i python.deb || {
    echo "安装失败，尝试修复依赖..."
    apt --fix-broken install -y
    dpkg -i python.deb || {
        echo "Python安装失败，使用系统Python"
        pkg install python -y
    }
}
rm -f python.deb

# 4. pip安装flask bs4 requests
echo "正在安装Python依赖..."
pip install --upgrade pip
pip install flask bs4 requests || {
    echo "pip安装失败，尝试使用--break-system-packages..."
    pip install --break-system-packages flask bs4 requests
}

# 5. 下载源代码
echo "正在下载并解压源代码..."
wget https://cccimg.com/down.php/5b06e5cf9bc7ef2d1f91d37a5ac54f75.zip -O EmuAIO.zip && {
    unzip -j EmuAIO.zip -d .
    rm -f EmuAIO.zip
} || {
    echo "下载源代码失败"
    exit 1
}

# 读取版本信息
if [ -f "EmuAIO/Version.txt" ]; then
    version=$(cat EmuAIO/Version.txt)
    echo "当前版本: $version"
else
    echo "未找到版本文件 EmuAIO/Version.txt"
fi

# 6. 创建快捷命令
echo "创建快捷命令Emu..."
echo '#!/data/data/com.termux/files/usr/bin/bash' > $PREFIX/bin/Emu
echo 'python ./EmuAIO/Html.py $@' >> $PREFIX/bin/Emu
chmod +x $PREFIX/bin/Emu

# 7. 尝试打开浏览器
echo "尝试打开浏览器..."
am start -a android.intent.action.VIEW -d http://127.0.0.1:5555 > /dev/null 2>&1 || {
    echo "无法自动打开浏览器，请手动访问: http://127.0.0.1:5555"
}

echo "安装完成！"
echo "启动方式:"
echo "1. 直接运行命令: Emu"
echo "2. 浏览器访问: http://127.0.0.1:5555"