#!/bin/bash

echo "🔧 配置 Java 17 环境变量..."

# 检查 Java 17 是否已安装
if [ -d "/Library/Java/JavaVirtualMachines/jdk-17.jdk" ]; then
    JAVA17_HOME="/Library/Java/JavaVirtualMachines/jdk-17.jdk/Contents/Home"
elif [ -d "/opt/homebrew/opt/openjdk@17" ]; then
    JAVA17_HOME="/opt/homebrew/opt/openjdk@17"
else
    echo "❌ 未找到 Java 17 安装目录"
    echo "请先安装 Java 17："
    echo "1. 访问 https://www.oracle.com/java/technologies/downloads/#java17"
    echo "2. 下载 macOS Arm 64 DMG Installer"
    echo "3. 安装后重新运行此脚本"
    exit 1
fi

echo "✅ 找到 Java 17 安装目录: $JAVA17_HOME"

# 检查当前 shell
if [ -n "$ZSH_VERSION" ]; then
    SHELL_CONFIG="$HOME/.zshrc"
elif [ -n "$BASH_VERSION" ]; then
    SHELL_CONFIG="$HOME/.bash_profile"
else
    SHELL_CONFIG="$HOME/.profile"
fi

echo "📝 配置文件: $SHELL_CONFIG"

# 备份现有配置
if [ -f "$SHELL_CONFIG" ]; then
    cp "$SHELL_CONFIG" "${SHELL_CONFIG}.backup.$(date +%Y%m%d_%H%M%S)"
    echo "✅ 已备份现有配置文件"
fi

# 移除旧的 JAVA_HOME 配置
if [ -f "$SHELL_CONFIG" ]; then
    sed -i '' '/export JAVA_HOME=/d' "$SHELL_CONFIG"
    sed -i '' '/export PATH.*JAVA_HOME/d' "$SHELL_CONFIG"
fi

# 添加新的 Java 17 配置
echo "" >> "$SHELL_CONFIG"
echo "# Java 17 Configuration" >> "$SHELL_CONFIG"
echo "export JAVA_HOME=\"$JAVA17_HOME\"" >> "$SHELL_CONFIG"
echo "export PATH=\"\$JAVA_HOME/bin:\$PATH\"" >> "$SHELL_CONFIG"

echo "✅ 已更新 $SHELL_CONFIG"

# 应用配置
source "$SHELL_CONFIG"

echo ""
echo "🎉 Java 17 环境变量配置完成！"
echo ""
echo "请运行以下命令使配置生效："
echo "source $SHELL_CONFIG"
echo ""
echo "或者重新打开终端窗口"
echo ""
echo "验证配置："
echo "java -version"
echo "echo \$JAVA_HOME"
