#!/bin/bash
set -fo pipefail

host=""
protocol=""
socket=""

# check if enhanced getopt is present to parse the args.
# If it is not, just use defaults
getopt --test > /dev/null 2>&1
EXITCODE=$?

# set -e for safety. (stops the whole script if any command fails)
# Cannot set -e before as getopt returns 4 in case of success
set -e

unparsed=( "$@" )

if [ $EXITCODE -eq 4 ]; then
  # only -h (host) and -S (socket) are used, the rest are parsed to prevent getopt from parsing their
  # arguments as other flags (e.g. -p'hpass' would lead to getopt generating '-h' 'text' if we didn't parse -p.)
  # See https://memsql.atlassian.net/browse/PLAT-5857 for an example.
  # Only flags that can have an argument must be parsed because of this
  OPTIONS=:h:S:D:e:p::P:u:
  LONGOPTS=host:,socket:,protocol:

  # pass arguments only via   -- "$@"   to separate them correctly.
  # We ignore error because we only parse some of the args.
  # getopt will return non-zero because of the unknown args, but it will still
  # parse the known ones correctly
  PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name "$0" -- "$@" || true)

  # read getopt’s output this way to handle the quoting right.
  # Append original options at the end to not lose them and pass to actual binary directly
  eval set -- "$PARSED"

  while true; do
      case "$1" in
          -h|--host)
              host="$2"
              shift 2
              ;;
          -S|--socket)
              socket="$2"
              shift 2
              ;;
          --protocol)
              protocol="$2"
              shift 2
              ;;
          # skip irrelevant flags
          -D|-e|-p|-P|-u)
              shift 2
              ;;
          --)
              shift
              break
              ;;
          *)
              echo "Unexpected error when parsing arguments"
              exit 1
              ;;
      esac
  done

  # convert to lowercase
  protocol=$(echo "$protocol" | awk '{ print tolower($0) }')

  if [ -n "$socket" ] || [ "$protocol" = "socket" ]; then
    # -h/--host=localhost tells mysql to use socket connection, all other values forces the use of TCP
    if [ -n "$host" ] && [ "$host" != "localhost" ]; then
      echo "-h/--host cannot be used with 'socket' protocol"
      exit 2
    fi

    if [ -n "$protocol" ] && [ "$protocol" != "socket" ]; then
      echo "--socket can only be used with 'socket' protocol"
      exit 2
    fi

    protocol="socket"
    host="localhost"
  fi
fi

CURRENT_DIR=$(dirname "$(readlink -f "${0}")")

default_args=('--no-defaults'
 "--plugin-dir=${CURRENT_DIR}/plugin"
 "--prompt=singlestore> "
 "-uroot"
 "-P3306")
[ -n "$protocol" ] && default_args+=( "--protocol=$protocol" ) || default_args+=( "--protocol=tcp" )
[ -n "$host" ] && default_args+=( "-h$host" )

exec "${CURRENT_DIR}/singlestore-client" \
    "${default_args[@]}" \
    "${unparsed[@]}"
