#!/bin/bash
# ============================================
# 项目环境初始化脚本
# 自动检测本机 Java 8 和 Android SDK，生成 local.properties
# ============================================
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

echo "=========================================="
echo "  环境检测 & local.properties 生成"
echo "=========================================="

# ---------- 1. 检测 Java 8 ----------
echo ""
echo "[1/3] 检测 Java 8 ..."

JAVA8_HOME=""
if command -v /usr/libexec/java_home &>/dev/null; then
    JAVA8_HOME=$(/usr/libexec/java_home -v 1.8 2>/dev/null || true)
fi

# 如果 /usr/libexec/java_home 找不到，手动扫描常见路径
if [ -z "$JAVA8_HOME" ]; then
    for candidate in \
        /Library/Java/JavaVirtualMachines/temurin-8.jdk/Contents/Home \
        /Library/Java/JavaVirtualMachines/jdk1.8.0_*.jdk/Contents/Home \
        /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home \
        /Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home; do
        for dir in $candidate; do
            if [ -f "$dir/bin/javac" ]; then
                JAVA8_HOME="$dir"
                break 2
            fi
        done
    done
fi

if [ -z "$JAVA8_HOME" ]; then
    echo "❌ 未找到 Java 8！本项目需要 JDK 8 才能编译。"
    echo "   请安装 JDK 8（推荐 temurin-8）："
    echo "   brew install --cask temurin8"
    echo ""
    echo "   安装后重新运行本脚本。"
    exit 1
fi
echo "✅ Java 8: $JAVA8_HOME"

# ---------- 2. 检测 Android SDK ----------
echo ""
echo "[2/3] 检测 Android SDK ..."

SDK_DIR=""

# 优先使用环境变量
if [ -n "$ANDROID_HOME" ] && [ -d "$ANDROID_HOME/platforms" ]; then
    SDK_DIR="$ANDROID_HOME"
elif [ -n "$ANDROID_SDK_ROOT" ] && [ -d "$ANDROID_SDK_ROOT/platforms" ]; then
    SDK_DIR="$ANDROID_SDK_ROOT"
fi

# macOS 常见路径
if [ -z "$SDK_DIR" ]; then
    for candidate in \
        "$HOME/Library/Android/sdk" \
        "/usr/local/share/android-sdk" \
        "$HOME/Android/Sdk"; do
        if [ -d "$candidate/platforms" ]; then
            SDK_DIR="$candidate"
            break
        fi
    done
fi

if [ -z "$SDK_DIR" ]; then
    echo "❌ 未找到 Android SDK！"
    echo "   请安装 Android Studio 或单独安装 Android SDK："
    echo "   https://developer.android.com/studio"
    echo ""
    echo "   安装后重新运行本脚本。"
    exit 1
fi
echo "✅ Android SDK: $SDK_DIR"

# ---------- 3. 生成 local.properties ----------
echo ""
echo "[3/3] 生成 local.properties ..."

cat > local.properties <<EOF
## 此文件由 setup.sh 自动生成，请勿手动修改
## 如需修改，请编辑后重新运行 setup.sh 或手动编辑
## $(date "+%Y-%m-%d %H:%M:%S")
sdk.dir=$SDK_DIR
EOF

echo "✅ local.properties 已生成"
echo ""
echo "=========================================="
echo "  环境就绪！运行以下命令构建项目："
echo "=========================================="
echo ""
echo "  export JAVA_HOME=$JAVA8_HOME"
echo "  ./gradlew compileDebugJavaWithJavac"
echo ""
echo "（每次新开终端都需要先 export JAVA_HOME）"
