#!/bin/bash


## 对外暴露的安装Redis的主函数
install_redis() {
  FunctionStart
  local redis_port="6379"
  local redis_install_method="binary"
  local redis_install_help="0"

  while [[ $# -gt 0 ]]; do
    case "$1" in
        -p | --port)
        redis_port="${2}"
        shift # past argument
        ;;
        -m | --method)
        redis_install_method="${2}"
        shift # past argument
        ;;
        -h | --help)
        redis_install_help="1"
        ;;
        *)
          echo "输入的内容有误，请检查！"
        # unknown option
        ;;
    esac
    shift # past argument or value
  done

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

  #    echo $redis_port
  #    echo $redis_install_method

    if [[ ${redis_install_method} == "binary" ]]; then
        install_redis_binary "${redis_port}"
  else
        install_redis_docker "${redis_port}"
  fi
    FunctionEnd
}

#######################################
# description
# Globals:
#   redis_port
# Arguments:
#   1
# Returns:
#   3 ...
#######################################
install_redis_binary() {
  redis_port=""
  if [[ $1 -ne " "   ]]; then
      redis_port="$1"
      echo "Redis Port = ${redis_port}"
  fi

  echo "InstallRedisBinary"

  CMD_REMOVE gcc
  installDemandSoftwares gcc wget

  echo "开始下载 Redis 6.2.6 的二进制包！"
  wget https://oss.107421.xyz/redis-6.2.6.tar.gz

  if [ -e redis-6.2.6.tar.gz ]; then
    echo "redis源码包下载完成！"
    echo ""
    echo "开始解压缩redis的安装包！"
    tar -zvxf redis-6.2.6.tar.gz
    cd redis-6.2.6
    clear
    echo ""
    echo ""
    echo "开始执行编译安装过程！！"
    echo "开始执行编译安装过程！！"
    echo "开始执行编译安装过程！！"
    echo "取决于服务器的性能，可能花费较长的时间！！！"
    sleep 3
    echo ""
    ./configure
    make && make install
    cd redis-6.2.6

    echo "Redis已经安装成功！！"
    ehco "开始进行redis的配置修改！！"
    wget https://oss.107421.xyz/redis-6.2.6.conf
    wget https://oss.107421.xyz/redis-server-6.2.6.service

    if [ -e redis-6.2.6.conf ] && [ -e redis-server-6.2.6.service ]; then
        echo "redis配置文件下载成功，开始进行修改！！"
        echo ""
        touch /var/log/redis_${redis_port}.log
        mkdir -p /var/redis/${redis_port}
        mkdir -p /etc/redis/

        sed -i "s/RedisPort/${redis_port}/g" redis-6.2.6.conf
        cp redis-6.2.6.conf /etc/redis/${redis_port}.conf

        sed -i "s/RedisPort/${redis_port}/g" redis-server-6.2.6.service
        cp redis-server-6.2.6.service /etc/init.d/redisd

        cd /etc/init.d
        chmod +x /etc/init.d/redisd

      if  command_exists chkconfig ; then
            chkconfig redisd on
      elif   command_exists update-rc.d ; then
            update-rc.d redisd defaults
      else
            echo "所需要的守护程序未安装，请手动设置！！"
      fi

        #  启动程序
        echo ""
        echo "开始启动redis-server服务……"
        service redisd start

        service redisd status

        netstat -ntlp | grep redis

    else
        echo "redis配置文件下载失败！！请手动进行修改！！"
        return 3
    fi
  else
    echo "redis源码包下载失败！"
    return 3
  fi

}

#######################################
# description
# Globals:
#   RED
#   redis_port
# Arguments:
#   1
# Returns:
#   3 ...
#######################################
install_redis_docker() {
  redis_port=""
  if [[ $1 -ne " "   ]]; then
      redis_port="$1"
      echo "Redis Port = ${redis_port}"
  fi

  echo "InstallRedisDocker"
  echo ""

  if ! command_exists "docker info" ; then
      colorEcho ${RED} "docker 未安装！！ 无法使用docker的方式安装 redis！"
      return 3
  fi

  echo "## 为redis配置添加 " >>/etc/sysctl.conf
  echo "vm.overcommit_memory = 1" >>/etc/sysctl.conf
  sysctl -p /etc/sysctl.conf

  echo "开始启动docker-redis !!"
      # https://hub.docker.com/r/bitnami/redis#configuration

  # 为redis设置密码  -e REDIS_PASSWORD=v2ryStr@ngPa.ss \
  docker run -d \
        -e ALLOW_EMPTY_PASSWORD=yes \
        -e REDIS_AOF_ENABLED=no \
        -e REDIS_PORT_NUMBER=${redis_port} \
        --name redis-server \
        --network host \
        bitnami/redis:6.2.6
}

InstallMysql() {
  FunctionStart
  MysqlPort="3306"
  MysqlInstallMethod="binary"
  MysqlInstallHelp="0"
  MysqlPersistData="/var/lib/docker/mysql-data"

  colorEcho ${BLUE} "本脚本默认安装版本为 8.0.27 的MySQL ！！"
  colorEcho ${BLUE} "本脚本默认安装版本为 8.0.27 的MySQL ！！"
  colorEcho ${BLUE} "本脚本默认安装版本为 8.0.27 的MySQL ！！"

  while [[ $# -gt 0 ]]; do
    case "$1" in
        -p | --port)
        MysqlPort="${2}"
        shift # past argument
        ;;
        -m | --method)
        MysqlInstallMethod="${2}"
        shift # past argument
        ;;
        -d | --data)
        MysqlPersistData="${2}"
        shift # past argument
        ;;
        -h | --help)
        MysqlInstallHelp="1"
        ;;
        *)
          echo "输入的内容有误，请检查！"
        # unknown option
        ;;
    esac
    shift # past argument or value
  done

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

  #    echo $MysqlPort
  #    echo $MysqlInstallMethod

    if [[ ${MysqlInstallMethod} == "binary" ]]; then
        installMysqlBinary ${MysqlPort}
  else
        installMysqlDocker ${MysqlPort} ${MysqlPersistData}
  fi

    FunctionEnd
}

installMysqlBinary() {
  MysqlPort=""
  Latest_Mysql_Version=""

  if [[ $1 -ne " "   ]]; then
      MysqlPort="$1"
      echo "mysql Port = ${MysqlPort}"
  fi

  echo "InstallMysqlBinary"

  if [[ ${LinuxReleaseVersion} == "centos"   ]]; then
      colorEcho ${BLUE} "当前系统发行版为 centos !"
      colorEcho ${BLUE} "开始安装mysql官方的yum源！！"
      echo ""
      rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm

      colorEcho ${BLUE} "可以安装的 mysql-server 版本为："
      yum list mysql-community-server | grep mysql-community-server
      echo ""
      Latest_Mysql_Version=$(yum list mysql-community-server | grep mysql-community-server | awk '{print $2}')
      colorEcho ${BLUE} "开始安装最新版本："
      installDemandSoftwares mysql-community-server-${Latest_Mysql_Version} mysql-community-server-${Latest_Mysql_Version}
  else
      colorEcho ${BLUE} "当前系统发行版为 ubuntu/debain !"
      colorEcho ${BLUE} "可以安装的  mysql-server 版本为："
      apt-cache madison mysql-server | awk '{print$3}'
      echo ""
      Latest_Mysql_Version=$(apt-cache madison mysql-server | head -n 1 | awk '{print$3}')
      colorEcho ${BLUE} "开始安装最新版本：${Latest_Mysql_Version}"

      installDemandSoftwares mysql-server=${Latest_Mysql_Version} mysql-client=${Latest_Mysql_Version}
  fi

      FunctionSuccess
      colorEcho ${BLUE} "准备启动Mysql Server的服务  ！！！"
      systemctl start mysqld
      FunctionSuccess
      colorEcho ${BLUE} "准备配置Mysql 服务的开机启动 ！！！"
      systemctl enable mysqld
      FunctionSuccess
}

installMysqlDocker() {
  MysqlPort=""
  MysqlPersistData=""

  MysqlPort="$1"
  echo "mysql Port = ${MysqlPort}"

  MysqlPersistData="$2"
  echo "mysql persist data path = ${MysqlPersistData}"

  echo "InstallMysqlDocker"
  echo ""

  echo "开始启动docker-mysql !!"
      # https://hub.docker.com/r/bitnami/mysql#configuration
  # 需要准备一个目录方式 mysql.conf文件
    # 目录权限需要处理
    mkdir -p ${MysqlPersistData}
    chown -R 1001:1001 ${MysqlPersistData}

    docker run -d \
        -e MYSQL_ROOT_USER=root \
        -e MYSQL_ROOT_PASSWORD=v2ryStr@ngPa.ss \
        -e MYSQL_CHARACTER_SET=utf8mb4 \
        -e MYSQL_COLLATE=utf8mb4_bin \
        -e MYSQL_DATABASE=demo \
        -e MYSQL_USER=wdd \
        -e MYSQL_PASSWORD=wdd14Fk@Clever \
        -e MYSQL_PORT_NUMBER=${MysqlPort} \
        -e MYSQL_AUTHENTICATION_PLUGIN=mysql_native_password \
        -v ${MysqlPersistData}:/bitnami/mysql/data \
        --name mysql-server \
        --network host \
        bitnami/mysql:8.0.27-debian-10-r40

}

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

  while [[ $# -gt 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
    FunctionEnd
}

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://oss-s1.107421.xyz/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://oss.107421.xyz/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 ""

  if [[ ${LinuxReleaseVersion} == "centos"   ]]; then
      colorEcho ${BLUE} "当前系统发行版为 centos !"
      colorEcho ${BLUE} "可以安装的  openjdk 版本为："
      yum list java-${JDK_VERSION}-openjdk | grep ${JDK_VERSION}
      echo ""
      colorEcho ${BLUE} "开始安装最新版本：$(yum list java-${JDK_VERSION}-openjdk | grep ${JDK_VERSION} | awk '{print $2}' | cut -d':' -f2 | head -n 1)"
      installDemandSoftwares java-${JDK_VERSION}-openjdk-$(yum list java-${JDK_VERSION}-openjdk | grep ${JDK_VERSION} | awk '{print $2}' | cut -d':' -f2 | head -n 1)
  else
      colorEcho ${BLUE} "当前系统发行版为 ubuntu/debain !"
      colorEcho ${BLUE} "可以安装的  openjdk 版本为："
      apt-cache madison openjdk-${JDK_VERSION}-jdk | awk '{print$3}'
      echo ""
      colorEcho ${BLUE} "开始安装最新版本：$(apt-cache madison openjdk-${JDK_VERSION}-jdk | head -n 1 | awk '{print$3}')"

      installDemandSoftwares openjdk-${JDK_VERSION}-jdk=$(apt-cache madison openjdk-${JDK_VERSION}-jdk | head -n 1 | awk '{print$3}')

  fi

  colorEcho ${BLUE} "请检查下面的内容输出！！！"
  java -version

}

install_golang_1.21.3(){
    FunctionStart "开始安装Golang运行环境！"

    wget --timeout=10 -q https://go.dev/dl/go1.21.3.linux-amd64.tar.gz

    rm -rf /usr/local/go && tar -C /usr/local -xzf go1.21.3.linux-amd64.tar.gz

    log "开始配置环境变量！"
    sed -i "$ a export GOPATH=/usr/local/go" /etc/profile
    sed -i "$ a PATH=$PATH:/usr/local/go/bin" /etc/profile

    source /etc/profile

    log "查看golang的版本！"
    go version

}
