#!/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)
if test $? -ne 0; then
    echo "Failed to get CloudFormation stack"
    exit 1
fi
if [[ ! -z $stacks ]]; then
    echo "Existing old deployment stacks, please remove them first. Stacks: \n$stacks"
    exit 1
fi
echo "$eksctlConfig" | eksctl create cluster --profile=$profile --write-kubeconfig -f - "$@"
