#!/bin/bash



# 需要实现的功能--指定端口 安装Mysql
## 二进制的安装方式
## docker的安装方式

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

  while [[ $# > 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
    fi

#    echo $MysqlPort
#    echo $MysqlInstallMethod

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

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

  echo "InstallMysqlBinary"

}

InstallMysqlDocker(){
  MysqlPort=""
  MysqlPersistData=""
  
  if [[ "$1" -ne " " ]]; then
      MysqlPort="$1"
      echo "mysql Port = ${MysqlPort}"
  fi
  
  if [[ "${2}" -ne " " ]]; then
      MysqlPersistData="$2"
      echo "mysql persist data path = ${MysqlPersistData}"
  fi

  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

}


InstallMysql -p 33306 -m docker -d "/var/lib/docker/mysql-pv"