#!/bin/bash

SHORT="c:,v:,s:,b:,r:,f:,h"
LONG="cluster-version:,size:,branch:,repository:,force-cluster,help"
OPTS=$(getopt -a -n create --options $SHORT --longoptions $LONG -- "$@")

eval set -- "$OPTS"

HERE=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
ROOT=$(dirname $(dirname ${HERE}))

# Source shared helper scripts
. $ROOT/shared/scripts/helpers.sh

# Defaults
CLUSTER_NAME="flux-cluster"
CLUSTER_VERSION="1.23"
MACHINE_TYPE="n1-standard-1"
FORCE_CLUSTER="false"
SIZE=4
TAGS=flux-cluster
REPOSITORY="flux-framework/flux-operator"
BRANCH="main"

function usage() {
   echo "This is the MiniKube kubernetes cluster creator."
   echo "usage: cluster-create --cluster <cluster-name> --size <size>"
}

while :
do
  case "$1" in
    -c | --cluster)
        CLUSTER_NAME=$2
        shift 2
        ;;
    -v | --cluster-version)
        CLUSTER_VERSION=$2
        shift 2
        ;;
    -t | --tags)
        TAGS=$2
        shift 2
        ;;
    -f | --force-cluster)
        FORCE_CLUSTER="true"
        shift 1
        ;;
    -s | --size)
        SIZE=$2
        shift 2
        ;;
    -b | --branch)
        BRANCH=$2
        shift 2
        ;;
    -r | --repository)
        REPOSITORY=$2
        shift 2
        ;;
    -h | --help)
      usage
      exit 2
      ;;
    --)
      shift;
      break
      ;;
    *)
      echo "Unexpected option: $1"
      ;;
  esac
done

print_magenta "   cluster  : ${CLUSTER_NAME}"
print_magenta "    version : ${CLUSTER_VERSION}"
print_magenta "    size   : ${SIZE}"
print_magenta "repository  : ${REPOSITORY}"
print_magenta "     branch : ${BRANCH}"

is_installed minikube
is_installed wget

# Check if it already exists
minikube status
retval=$?
if [[ "${retval}" == "0" ]]; then
    print_blue "A MiniKube cluster already exists."
    echo
    exit 0
fi

if [[ "${FORCE_CLUSTER}" != "true" ]]; then
    prompt "Do you want to create this cluster?"
fi

# Create the cluster
run_echo minikube start --nodes=${SIZE}

# Show nodes
run_echo kubectl get nodes

# Deploy the operator TODO should be variables here
tmpfile=$(mktemp /tmp/flux-operator.XXXXXX.yaml)
rm -rf $tmpfile
run_echo wget -O $tmpfile https://raw.githubusercontent.com/${REPOSITORY}/${BRANCH}/examples/dist/flux-operator.yaml
kubectl apply -f $tmpfile
rm -rf $tmpfile

run_echo kubectl get namespace
run_echo kubectl describe namespace operator-system
