#!/usr/bin/env bash
# filename: jdk_install.sh

jdk_url="http://wd:wd@soft.ddos.com/tarball/java/server-jre-8u181-linux-x64.tar.gz"
jdk_md5sum="5c8092c606ef28c2e3ad850354a2c53a"
jdk_src_dir=/opt/wd/src
jdk_app_dir=/opt/wd/app

function install() {
    [[ -e ${jdk_src_dir} ]] || mkdir -pv ${jdk_src_dir}
    [[ -e ${jdk_app_dir} ]] || mkdir -pv ${jdk_app_dir}
    [[ -e /tmp/${jdk_url##*/} ]] || curl -L ${jdk_url} -o /tmp/${jdk_url##*/}

    echo "${jdk_md5sum} /tmp/${jdk_url##*/}" | md5sum -c
    if [[ $? != '0' ]]; then
        echo "Error: Failed to check the file";
        rm -rf /tmp/kafka_${kafka_ver}.tar.gz
        exit 67
    fi

    tar axvf /tmp/${jdk_url##*/} -C ${jdk_src_dir}
    cd ${jdk_app_dir} && [[ -L ${jdk_app_dir}/jdk ]] && rm -rf jdk
    ln -sv ../src/jdk1.8.0_181 ./jdk

    update-alternatives --install /usr/bin/java java ${jdk_app_dir}/jdk/bin/java 100
    update-alternatives --install /usr/bin/javac javac ${jdk_app_dir}/jdk/bin/javac 100
}

function remove() {
    update-alternatives --remove java ${jdk_app_dir}/bin/java
    update-alternatives --remove javac ${jdk_app_dir}/bin/javac

    rm -rf ${jdk_app_dir}/jdk ${jdk_src_dir}/jdk1.8.0_181
}

case $1 in
    install|-i)
        install
        ;;
    remove|-r)
        remove
        ;;
    *)
        echo "Usage: $(basename $0 .sh)  install | remove"
esac
