#!/bin/bash

# 检测并修复所需的依赖项
check_dependencies() {
    local dependencies=("wget" "rpm")

    for dependency in "${dependencies[@]}"; do
        if ! command -v "$dependency" &>/dev/null; then
            echo "正在安装所需的依赖项：$dependency"
            sudo yum install -y "$dependency"
        fi
    done
}

# 显示版本选择菜单
show_version_menu() {
    echo "请选择要安装的Java版本："
    echo "1. JDK 8u381"
    echo "2. JDK 11.0.20"
    echo "3. JDK 17"
    echo "4. JDK 20"
    echo "5. JRE 8u381"
    echo
}

# 获取用户选择的版本
get_version_choice() {
    read -p "请输入选项(1-5): " choice

    case $choice in
        1) java_package="jdk-8u381-perf-linux-x64.rpm" ;;
        2) java_package="jdk-11.0.20_linux-x64_bin.rpm" ;;
        3) java_package="jdk-17_linux-x64_bin.rpm" ;;
        4) java_package="jdk-20_linux-x64_bin.rpm" ;;
        5) java_package="jre-8u381-linux-x64.rpm" ;;
        *) echo "无效的选项，请重新选择。" ; get_version_choice ;;
    esac
}

# 检测并卸载已安装的Java
uninstall_java() {
    echo "正在卸载已安装的Java..."
    sudo yum remove -y java
    sudo rm -rf /usr/bin/java
    echo "已卸载已安装的Java"
    echo
}

# 检测系统是否已安装Java
java_installed=false
java_version=""
java_directory=""

if command -v java &>/dev/null; then
    java_installed=true
    java_version=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}')
    java_directory=$(dirname $(readlink -f $(which java)))
fi

# 输出已安装的Java版本和安装目录信息
if $java_installed; then
    echo "已检测到已安装的Java版本：$java_version"
    echo "安装目录：$java_directory"
    echo

    # 询问是否需要卸载已安装的Java
    read -p "是否需要卸载已安装的Java？(y/n): " uninstall_choice

    if [[ $uninstall_choice == "y" || $uninstall_choice == "Y" ]]; then
        # 卸载已安装的Java
        uninstall_java
    else
        echo "终止安装过程。"
        exit 0
    fi
fi

# 检测并安装所需的依赖项
check_dependencies

# 显示版本选择菜单并获取用户选择的版本
show_version_menu
get_version_choice

# 下载Java安装包
java_package_url="http://xiutu.us/java/$java_package"

echo "正在下载Java安装包..."
wget -q $java_package_url -O $java_package

# 卸载已安装的Java
uninstall_java

# 安装Java
java_directory="/usr/bin/java"

sudo mkdir -p $java_directory
sudo cp $java_package $java_directory
cd $java_directory
sudo rpm -ivh $java_package

# 删除安装包
sudo rm $java_package

# 输出安装完成信息
installed_java_version=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}')
installed_java_directory="/usr/bin/java"

echo "Java已成功安装到$installed_java_directory"
echo "已安装的Java版本：$installed_java_version"
