#!/bin/bash -u

# Turn off shell globbing (because we do SQL querying below)
set -o noglob

function usage() {
    local path=$0
    cat << EOF
Usage example:
  $ ${path##*/} [options] <query>

  This tool is used to enable/disable the specified scheduler that matches the write-hg.

  Options:
    --write-hg=<hostgroup>  : the write hostgroup (specifies the scheduler to be enabled/disabled)
    --enable                : activate the scheduler (default)
    --disable               : deactivate the scheduler
    --user=<user>           : specify the user name
    --password=<password>   : specify the user password
    --host=<host>           : specify host address
    --port=<port>           : specify host port
    --query-options=<options> : mysql client command line options, (example: "--silent -N")

  Examples:
    ${path##*/} --enable --write-hg=10

  The default is to use the ProxySQL credentials in /etc/proxysql-admin.cnf.

EOF
}

#
# Executes an SQL query
#
# Globals:
#   USER
#   PASSWORD
#   HOST
#   PORT
#
# Arguments:
#   1: arguments to be passed to mysql
#   2: the query
#
function exec_sql() {
  local args=$1
  local query=$2
  local retvalue
  local retoutput

  retoutput=$(printf "[client]\nuser=${USER}\npassword=\"${PASSWORD}\"\nhost=${HOST}\nport=${PORT}"  \
      | mysql --defaults-file=/dev/stdin --protocol=tcp \
            ${args} -e "${query}")
  retvalue=$?

  printf "${retoutput//%/%%}"
  return $retvalue
}


declare USER=""
declare PASSWORD=""
declare HOST=""
declare PORT=""
declare WRITE_HG=""
declare ENABLE=1

function parse_args() {
  local param value
  local positional_params=""

  while [[ $# -gt 0 && "$1" != "" ]]; do
      param=`echo $1 | awk -F= '{print $1}'`
      value=`echo $1 | awk -F= '{print $2}'`

      # Assume that all options start with a '-'
      # otherwise treat as a positional parameter
      if [[ ! $param =~ ^- ]]; then
        positional_params+="$1 "
        shift
        continue
      fi
      case $param in
        -h | --help)
          usage
          exit
          ;;
        --user)
          USER=$value
          ;;
        --password)
          PASSWORD=$value
          ;;
        --host)
          HOST=$value
          ;;
        --port)
          PORT=$value
          ;;
        --write-hg)
          WRITE_HG=$value
          ;;
        --enable)
          ENABLE=1
          ;;
        --disable)
          ENABLE=0
          ;;
        *)
          echo "ERROR: unknown parameter \"$param\""
          usage
          exit 1
          ;;
      esac
      shift
  done
}


if [[ -r /etc/proxysql-admin.cnf ]]; then
  source /etc/proxysql-admin.cnf
  USER=$PROXYSQL_USERNAME
  PASSWORD=$PROXYSQL_PASSWORD
  HOST=$PROXYSQL_HOSTNAME
  PORT=$PROXYSQL_PORT
fi

parse_args "$@"
if [[ -z $WRITE_HG ]]; then
  echo "Error: Must specify a write hostgroup"
  exit 1
fi

exec_sql "" "UPDATE scheduler SET active=$ENABLE WHERE ARG1 LIKE '% --write-hg=$WRITE_HG %'; LOAD scheduler TO RUNTIME"
if [[ $? -ne 0 ]]; then
  echo "scheduler update failed"
  exit 1
fi

value=$(exec_sql "-Ns" "SELECT active FROM scheduler WHERE ARG1 LIKE '% --write-hg=$WRITE_HG %'")
echo "        scheduler active value for write hostgroup $WRITE_HG : $value"
value=$(exec_sql "-Ns" "SELECT active FROM runtime_scheduler WHERE ARG1 LIKE '% --write-hg=$WRITE_HG %'")
echo "runtime scheduler active value for write hostgroup $WRITE_HG : $value"
