#!/bin/bash
set -o pipefail

args=$1
profile=$2
shift 2

k8sName=$(echo "$args" | yq ".k8s.name")
region=$(echo "$args" | yq ".region.region")
templateFile=$(echo "$args" | yq '.k8s.template-path')
echo "k8sName=$k8sName"
echo "region=$region"
echo "templateFile=$templateFile"

eksctlConfig=$(echo "$args" | gomplate -c .=stdin:///in.yml -f "$templateFile")
if test $? -ne 0; then
    echo "Failed to render eksctl config"
    exit 1
fi
echo -e "EKS Config: \n$eksctlConfig"

stacks=$(aws cloudformation describe-stacks \
   --query "Stacks[?starts_with(StackName, 'eksctl-$k8sName-')].[StackName]" \
   --profile=$profile --region=$region  --output=text --no-cli-pager)
echo "stacks $stacks"
if test $? -ne 0; then
    echo "Failed to get CloudFormation stack"
    exit 1
fi
if [[ ! -z $stacks ]]; then
    echo "$eksctlConfig" | eksctl delete cluster --profile=$profile -f - --wait "$@"
fi