#!/bin/bash
# This script will create kuberneties cluster and install ingress controller.

#set -x
#printenv | sort
#echo ; echo

# passing configuration file eg : az10-create_aks_cluster.sh  bnz-uat.conf | az10-create_aks_cluster.sh  bnz-prd.conf | az10-create_aks_cluster.sh tst.conf
path_script="$(readlink -f "$0")"
path_dir="${path_script%/*}"
source ${1:-$path_dir/az-dev.conf}
fn=`basename "$0"`

if [ -f "$2" ]; then #Local debug credentials in 2nd file not in git
  echo " ##!!!## source second file $2"
  source $2
  #
  if [[ "$DebugAZlogin" = true ]]; then
    echo "#$fn: az login --service-principal --username $SP_DEPLOY_ID --tenant $TENANT"
    az login  --service-principal \
              --username $SP_DEPLOY_ID \
              --password $SP_DEPLOY_SECRET \
              --tenant $TENANT
    echo "#$fn: az account set --subscription $SUBSCRIPTIONID"
    az account set --subscription $SUBSCRIPTIONID
  fi
fi


#Pick default pub ssh key if not set.
AKSCLUSTERSSHKEYPATH="${AKSCLUSTERSSHKEYPATH:-$path_dir/pub_key.pub}"

# check the resouces availability from az pipeline
# Optional: RESERVEDPUBIPADDR / RESERVEDPUBIPADDRNAME / (SKU set to Standard for LB and IP's)
for resource in TENANT SUBSCRIPTIONID AKSENVIRONMENT CH CHANNELTAG AKSCLUSTERNAME AKSCLUSTERNODECOUNT AKSCLUSTERADDONS RESOURCELOCATION ;
do
  if [ -z "${!resource}" ]; then
    echo "####$fn: $resource Not found. Check pipeline variables"
    exit 1;
  fi
done

#Sku Standard or Basic
aksLbSku="${AKSCLUSTERLBSKU:-Standard}"

aksResourceGroup=${AKSCLUSTERRESOURCEGROUP:-aks-$AKSCLUSTERNAME}

echo "####$fn:#### create aks_pub_ip  ####"


  # finding public IP or use from config
  if [ -z "$RESERVEDPUBIPADDR" ]; then
      # check $RESERVEDPUBIPADDRNAME define in config file
      if [ -z "$RESERVEDPUBIPADDRNAME" ]; then
          aksClusterPubIPName=$AKSCLUSTERNAME-$AKSENVIRONMENT-ip-public
          echo "####$fn: No RESERVEDPUBIPADDRNAME set , pick aksClusterPubIPName=$aksClusterPubIPName"
      else
          aksClusterPubIPName=$RESERVEDPUBIPADDRNAME
          echo "####$fn: use env RESERVEDPUBIPADDRNAME=$aksClusterPubIPName"
      fi

      # check $RESERVEDPUBIPRESOURCEGROUP define in config file, used in ingress creation
      if [ -z "$RESERVEDPUBIPRESOURCEGROUP" ]; then
          pubIPResGrp=$aksResourceGroup
          echo "####$fn: No RESERVEDPUBIPRESOURCEGROUP set , lookup pubIPResGrp=$pubIPResGrp"
      else
          pubIPResGrp=$RESERVEDPUBIPRESOURCEGROUP
          echo "####$fn: use env RESERVEDPUBIPRESOURCEGROUP=$RESERVEDPUBIPRESOURCEGROUP"
      fi

      # get the pub ip address
      aksClusterPubIPsku=$(az network public-ip show --resource-group $pubIPResGrp \
                                                  --name $aksClusterPubIPName \
                                                  --query sku \
                                                  --output tsv)
      rc=$?
      if [[ rc -eq 0 ]]; then
        echo "####$fn: found ip, no need to create sku=$aksClusterPubIPsku"
      else
        ##Asume as we dont have PUB IP we also need RG
        aksClusterTags="environment=$AKSENVIRONMENT $CHANNELTAG"
        echo "###$fn: az group create --name $aksResourceGroup ($pubIPResGrp) --location $RESOURCELOCATION"
        az group create --name $aksResourceGroup --location $RESOURCELOCATION --tags $aksClusterTags

        echo "####$fn: rc=$rc, create ip, --sku $aksLbSku  --name $aksClusterPubIPName  --resource-group $pubIPResGrp"
        az network public-ip create --resource-group $pubIPResGrp \
                                    --name $aksClusterPubIPName \
                                    --allocation-method static \
                                    --location $RESOURCELOCATION \
                                    --sku $aksLbSku
                                    #: Public IP SKU.  Allowed values: Basic, Standard.
                                    # Need Standard IP to match Standard LB to allow for k8s API whitelist
        # get the pub ip address
      fi
      aksClusterPubIP=$(az network public-ip show --resource-group $pubIPResGrp \
                                                  --name $aksClusterPubIPName \
                                                  --query ipAddress \
                                                  --output tsv)
      echo "####$fn: got aksClusterPubIP=$aksClusterPubIP"
      # get the pub ip subscription id (used to add lock to pub ID below)
      aksClusterPubIpID=$(az network public-ip show --resource-group $pubIPResGrp \
                                                  --name $aksClusterPubIPName \
                                                  --query id \
                                                  --output tsv)
      # query and check the pub ip address
      if [ -z "$aksClusterPubIP" ]; then
        echo "####$fn: aksClusterPubIP can't be empty!!! Error on public IP creation"
        exit 1;
      else
        echo "####$fn: az lock show --name deleteLock-$aksClusterPubIPName --resource-group $pubIPResGrp --resource-name $aksClusterPubIPName --resource-type Microsoft.Network/publicIPAddresses -o table"
        #az lock show --name deleteLock-$aksClusterPubIPName --resource-group $aksResourceGroup -o table
        az lock show  --name deleteLock-$aksClusterPubIPName \
                      --resource-group $pubIPResGrp \
                      --resource-name $aksClusterPubIPName \
                      --resource-type Microsoft.Network/publicIPAddresses \
                      -o table
                      #--subscription ""
        rc=$?;
        if [[ $rc -ne 0 ]]; then
          echo "####$fn: Adding Delete lock to $aksClusterPubIPName along with $aksClusterPubIP using id $aksClusterPubIpID"
          az lock create  --name deleteLock-$aksClusterPubIPName \
                          --lock-type CanNotDelete \
                          --resource $aksClusterPubIpID
        fi
    fi

  else
    echo "####$fn: use aksClusterPubIP as RESERVEDPUBIPADDR - $RESERVEDPUBIPADDR"
    aksClusterPubIP=$RESERVEDPUBIPADDR
  fi
