#!/bin/bash
set -euo pipefail

SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"
PLATFORM=$(uname | tr '[:upper:]' '[:lower:]')
TEST_ID=$(uuidgen | cut -d'-' -f1 | tr '[:upper:]' '[:lower:]')
CLUSTER_NAME_BASE=$(uuidgen | cut -d'-' -f1 | tr '[:upper:]' '[:lower:]')
OVERRIDE_PATH=0
KIND_CONFIG_FILE=$SCRIPTPATH/kind-three-node-cluster.yaml

# shellcheck disable=SC2034
K8_1_21="kindest/node:v1.21.1@sha256:69860bda5563ac81e3c0057d654b5253219618a22ec3a346306239bba8cfa1a6"
# shellcheck disable=SC2034
K8_1_20="kindest/node:v1.20.70@sha256:cbeaf907fc78ac97ce7b625e4bf0de16e3ea725daf6b04f930bd14c67c671ff9"
# shellcheck disable=SC2034
K8_1_19="kindest/node:v1.19.11@sha256:07db187ae84b4b7de440a73886f008cf903fcf5764ba8106a9fd5243d6f32729"
# shellcheck disable=SC2034
K8_1_18="kindest/node:v1.18.19@sha256:7af1492e19b3192a79f606e43c35fb741e520d195f96399284515f077b3b622c"
# shellcheck disable=SC2034
K8_1_17="kindest/node:v1.17.17@sha256:66f1d0d91a88b8a001811e2f1054af60eef3b669a9a74f9b6db871f2f1eeed00"
# shellcheck disable=SC2034
K8_1_16="kindest/node:v1.16.15@sha256:83067ed51bf2a3395b24687094e283a7c7c865ccc12a8b1d7aa673ba0c5e8861"

K8_VERSION="$K8_1_20"
KUBECTL_VERSION=$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)
KIND_VERSION="0.11.1"
HELM_VERSION="3.6.0"

echoerr() { echo "$@" 1>&2; }

USAGE=$(cat << 'EOM'
  Usage: provision-cluster  [-b <BASE_CLUSTER_NAME>] [-i <TEST_IDENTIFIER>] [-v K8s_VERSION] [-o]
  Executes the spot termination integration test for the Node Termination Handler.
  Outputs the cluster context directory to stdout on successful completion

  Example: provision-cluster -b my-test -i 123 -v 1.20

          Optional:
            -b          Base Name of cluster
            -i          Test Identifier to suffix Cluster Name and tmp dir
            -v          K8s version to use in this test
            -k          Kind cluster config file
            -o          Override path w/ your own kubectl and kind binaries
EOM
)

# Process our input arguments
while getopts "b:i:v:k:o" opt; do
  case ${opt} in
    b ) # BASE CLUSTER NAME
        CLUSTER_NAME_BASE=$OPTARG
      ;;
    i ) # Test ID
        TEST_ID=$OPTARG
        echoerr "👉 Test Run: $TEST_ID 👈"
      ;;
    v ) # K8s version to provision
        OPTARG="K8_`echo $OPTARG | sed 's/\./\_/g'`"
        if [ ! -z ${OPTARG+x} ]; then
            K8_VERSION=${!OPTARG}
        else
            echoerr "K8s version not supported"
            exit 2
        fi
      ;;
    k ) # Kind cluster config file
        KIND_CONFIG_FILE=$OPTARG
      ;;
    o ) # Override path with your own kubectl and kind binaries
	    OVERRIDE_PATH=1
      ;;
    \? )
        echoerr "$USAGE" 1>&2
        exit
      ;;
  esac
done

CLUSTER_NAME="$CLUSTER_NAME_BASE"-"$TEST_ID"
TMP_DIR=$SCRIPTPATH/../../build/tmp-$CLUSTER_NAME

echoerr "🐳 Using Kubernetes $K8_VERSION"
mkdir -p $TMP_DIR

deps=("docker")

for dep in "${deps[@]}"; do
    path_to_executable=$(which $dep)
    if [ ! -x "$path_to_executable" ]; then
        echoerr "You are required to have $dep installed on your system..."
        echoerr "Please install $dep and try again. "
        exit 3
    fi
done

## Append to the end of PATH so that the user can override the executables if they want
if [[ OVERRIDE_PATH -eq 1 ]]; then
   export PATH=$PATH:$TMP_DIR
else
  if [ ! -x "$TMP_DIR/kubectl" ]; then
      echoerr "🥑 Downloading the \"kubectl\" binary"
      retry 5 curl -Lo $TMP_DIR/kubectl "https://storage.googleapis.com/kubernetes-release/release/$KUBECTL_VERSION/bin/$PLATFORM/amd64/kubectl"
      chmod +x $TMP_DIR/kubectl
      echoerr "👍 Downloaded the \"kubectl\" binary"
  fi

  if [ ! -x "$TMP_DIR/kind" ]; then
      echoerr "🥑 Downloading the \"kind\" binary"
      retry 5 curl -Lo $TMP_DIR/kind https://github.com/kubernetes-sigs/kind/releases/download/v$KIND_VERSION/kind-$PLATFORM-amd64
      chmod +x $TMP_DIR/kind
      echoerr "👍 Downloaded the \"kind\" binary"
  fi

  if [ ! -x "$TMP_DIR/helm" ]; then
      echoerr "🥑 Downloading the \"helm\" binary"
      retry 5 curl -L https://get.helm.sh/helm-v$HELM_VERSION-$PLATFORM-amd64.tar.gz | tar zxf - -C $TMP_DIR
      mv $TMP_DIR/$PLATFORM-amd64/helm $TMP_DIR/.
      chmod +x $TMP_DIR/helm
      echoerr "👍 Downloaded the \"helm\" binary"
  fi
  export PATH=$TMP_DIR:$PATH
fi

echoerr "🥑 Creating k8s cluster using \"kind\""
retry 3 kind create cluster -q --name "$CLUSTER_NAME" --image $K8_VERSION --config "$KIND_CONFIG_FILE" --kubeconfig $TMP_DIR/kubeconfig 1>&2

echo "$CLUSTER_NAME" > "$TMP_DIR/clustername"
echoerr "👍 Created k8s cluster using \"kind\""

kubectl apply -f "$SCRIPTPATH/psp-default.yaml" --context "kind-$CLUSTER_NAME" --kubeconfig "$TMP_DIR/kubeconfig" 1>&2
kubectl apply -f "$SCRIPTPATH/psp-privileged.yaml" --context "kind-$CLUSTER_NAME" --kubeconfig "$TMP_DIR/kubeconfig" 1>&2

echo "$TMP_DIR"
