#!/bin/bash
set -e

echo "=========================================="
echo "  Theos 越狱开发环境一键安装脚本"
echo "=========================================="
echo ""

# 设置 Theos 路径
export THEOS=/opt/theos

# 1. 安装依赖
echo "[1/5] 安装系统依赖..."
apt-get update
apt-get install -y clang rsync unzip curl build-essential git fakeroot libssl-dev

# 2. 克隆 Theos
echo "[2/5] 克隆 Theos 到 $THEOS..."
if [ -d "$THEOS" ]; then
    echo "Theos 已存在，跳过克隆"
else
    git clone --recursive https://github.com/theos/theos.git $THEOS
fi

# 3. 下载 iOS SDK
echo "[3/5] 下载 iOS SDK..."
SDK_DIR=$THEOS/sdks
mkdir -p $SDK_DIR

if [ ! -d "$SDK_DIR/iPhoneOS14.5.sdk" ]; then
    echo "下载 iPhoneOS 14.5 SDK..."
    curl -sL "https://github.com/theos/sdks/raw/master/iPhoneOS14.5.sdk.tar.xz" | tar -xJ -C $SDK_DIR
else
    echo "SDK 已存在，跳过下载"
fi

# 4. 下载并编译 ldid (签名工具)
echo "[4/5] 安装 ldid 签名工具..."
if ! command -v ldid &> /dev/null; then
    cd /tmp
    git clone https://github.com/haikentcode/ldid.git
    cd ldid
    ./build.sh
    cp ldid /usr/local/bin/
    chmod +x /usr/local/bin/ldid
    echo "ldid 安装完成"
else
    echo "ldid 已安装，跳过"
fi

# 5. 配置环境变量
echo "[5/5] 配置环境变量..."
cat >> ~/.bashrc << 'EOF'

# Theos 环境变量
export THEOS=/opt/theos
export PATH=$THEOS/bin:$PATH
EOF

source ~/.bashrc

echo ""
echo "=========================================="
echo "  ✅ Theos 环境配置完成！"
echo "=========================================="
echo ""
echo "验证安装："
echo "  echo \$THEOS"
echo "  which ldid"
echo ""
echo "编译插件："
echo "  cd /www/wwwroot/yyy.xmling.top/tweak-template/KeyboardTools"
echo "  make package"
echo ""
