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

#set -x #Debug
#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 "###$fn: !!!## source second file $2"
  source $2
fi

echo "###$fn: Home is : $HOME"
echo "###$fn: Running path : $PWD"
# running user
echo "###$fn: whoami=$(whoami)"

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

# check the resouces availability from az pipeline
for resource in SP_DEPLOY_ID SP_DEPLOY_SECRET SP_K8S_ID SP_K8S_SECRET TENANT SUBSCRIPTIONID CH AKSCLUSTERNAME ;
do
  if [ -z "${!resource}" ]; then
    echo "###$fn: $resource Not found. Check pipeline variables"
    exit 1
  fi
done

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

echo "###$fn: az --version"
azversion=$( az --version )

echo "$azversion" | grep "aks-preview"
rc=$?
if [[ $rc -ne 0 ]]; then
    echo "###$fn: az extention  \"aks-preview\" is available"
else
    echo "###$fn: az extention add/update"
    az extension add --name aks-preview  # Need aks-preview for --node-resource-group --enable-pod-security-policy
    az extension update --name aks-preview
    azversion=$( az --version )
    echo "###$fn: az --version | grep \"azure-cli\|aks-preview\" "
    echo azversion | grep "azure-cli\|aks-preview"
    ## Now create cluster ;
fi

# az login with service principal
echo "#####$fn: az login --service-principal --username $SP_DEPLOY_ID"
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
#echo "###$fn: az account list --output table"
#az account list --output table
echo "#$0 check availability of SP_K8S_ID=$SP_K8S_ID used for this k8s instance --name $AKSCLUSTERNAME"
az ad sp show --id $SP_K8S_ID > /dev/null
rc=$?
if [[ $rc -ne 0 ]]; then
    echo "#$0 cant find service principal to be used in cluster - SP_K8S_ID=$SP_K8S_ID"
    exit 1
fi
