#!/bin/bash

SHORT="c:,z:,f,h"
LONG="cluster:,zone:,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"
FORCE_CLUSTER="false"
ZONE="us-central1-a"

function usage() {
   echo "This is the Google Cloud kubernetes cluster destroyer."
   echo "usage: cluster-destroy --cluster <cluster-name> --zone <zone>"
}

while :
do
  case "$1" in
    -c | --cluster)
        CLUSTER_NAME=$2
        shift 2
        ;;
    -z | --zone)
        ZONE=$2
        shift 2
        ;;
    -h | --help)
      usage
      exit 2
      ;;
    -f | --force-cluster)
        FORCE_CLUSTER="true"
        shift 1
        ;;
    --)
      shift;
      break
      ;;
    *)
      echo "Unexpected option: $1"
      ;;
  esac
done

if [ -z ${ZONE+x} ]; then
    echo "Please provide your Google Cloud zone with --zone";
    exit 1
fi

echo "   cluster  : ${CLUSTER_NAME}"
echo "     zone   : ${ZONE}"

is_installed gcloud
is_installed yes || FORCE_CLUSTER="false"

# Check if it already exists
gcloud container clusters list --zone ${ZONE} | grep ${CLUSTER_NAME}
retval=$?
if [[ "${retval}" != "0" ]]; then
    print_blue "${CLUSTER_NAME} in ${ZONE} does not exist."
    echo
    exit 0
fi

# This command has a confirmation already
if [[ "${FORCE_CLUSTER}" == "true" ]]; then
    yes | gcloud container clusters delete --zone ${ZONE} ${CLUSTER_NAME}
else
    run_echo gcloud container clusters delete --zone ${ZONE} ${CLUSTER_NAME}
fi
