#!/bin/bash


# 需要实现的功能-- 指定安装的JDK版本，指定以
## 默认安装的版本为 Oracle-JDK 11.0.9
## 二进制的安装方式
## 源package的安装方式

## 对外暴露的安装JDK的主函数
InstallJDK(){
  JDK_VERSION="11"
  JDK_Install_Method="binary"
  JDKInstallHelp="0"

  while [[ $# > 0 ]]; do
    case "$1" in
        -v|--version)
        JDK_VERSION="${2}"
        shift # past argument
        ;;
        -m|--method)
        JDK_Install_Method="${2}"
        shift # past argument
        ;;
        -h|--help)
        JDKInstallHelp="1"
        ;;
        *)
          echo "输入的内容有误，请检查！"
        # unknown option
        ;;
    esac
    shift # past argument or value
    done

    if [ "${JDKInstallHelp}" -eq "1" ]; then
        cat - 1>& 2 << EOF
./install-release.sh [-h] [-p|--Version 6379] [-m|--method binary|docker]
  -h, --help            打印此安装帮助说明
  -v, --version         安装JDK的版本，如果不指定此参数，则默为11
  -m, --method          安装JDK的方式，binary == 源码编译安装，package == 使用源，package安装；不指定则使用binary
EOF
        return 0
    fi

#    echo $JDKVersion
#    echo $JDKInstallMethod

    if [[ ${JDK_Install_Method} == "binary" ]]; then
        InstallJDKBinary ${JDK_VERSION}
    else
        InstallJDKPackage ${JDK_VERSION}
    fi
}

InstallJDKBinary() {
  JDK_VERSION=""
  JDK_FILENAME=""
  if [[ "$1" -ne " " ]]; then
      JDK_VERSION="$1"
      echo "JDK Version = ${JDK_VERSION}"
  fi
  
  echo "InstallJDKBinary"
  echo ""

  echo "开始下载 JDK 的源码包！！"

  mkdir -p /usr/local/java/


  if [ "${JDK_VERSION}" -eq "11" ]; then
        JDK_FILENAME="jdk-11.0.9"
        wget https://objectstorage.ap-seoul-1.oraclecloud.com/n/cnk8d6fazu16/b/seoul/o/jdk-11.0.9_linux-x64_bin.tar.gz
        echo "JDK 二进制文件下载成功，开始解压缩！！"
        tar -zxvf jdk-11.0.9_linux-x64_bin.tar.gz -C /usr/local/java/

  else
        JDK_FILENAME="jdk1.8.0_271"
        wget https://objectstorage.ap-seoul-1.oraclecloud.com/n/cnk8d6fazu16/b/seoul/o/jdk-8u271-linux-x64.tar.gz
        echo "JDK 二进制文件下载成功，开始解压缩！！"
        tar -zxvf jdk-8u271-linux-x64.tar.gz -C /usr/local/java/
  fi

  echo ""
  echo "开始配置JDK的环境变量！！！"
  if [ -e /etc/profile.d/jdk-env.sh ]; then
      echo "jdk的配置文件已经存在！，将会进行覆盖操作！"
      cp /etc/profile.d/jdk-env.sh .jdk-env-backup.sh

      rm /usr/bin/java
  fi

  cat >/etc/profile.d/jdk-env.sh <<EOF
export JAVA_HOME=/usr/local/java/${JDK_FILENAME}
export JRE_HOME=${JAVA_HOME}/jre
export CLASSPATH=${JAVA_HOME}/lib:${JRE_HOME}/lib:${CLASSPATH}
export PATH=${JAVA_HOME}/bin:${JRE_HOME}/bin:${PATH}
EOF
        source /etc/profile
        ln -s /usr/local/java/${JDK_FILENAME}/bin/java /usr/bin/java

        echo ""
        echo ""
        echo ""
        echo "请检查JDK的安装情况======================================"
        java -version
}

InstallJDKPackage(){
  JDK_VERSION=""
  if [[ "$1" -ne " " ]]; then
      JDK_VERSION="$1"
      echo "JDK Version = ${JDK_VERSION}"
  fi

  echo "InstallJDKDocker"
  echo ""

   apt-cache madison openjdk-11-jdk

}


InstallJDK -v 11 -m binary