##############BUILD DOCKER IMAGE AND PUSH TO AZURE ACR REPOSITORY#########################
az login --service-principal --username $azureuser --password $azurepassword --tenant $azuretenantid
az acr login -n $AZUREACRNAME
DOCKERHUBURL=$(az acr show --name $AZUREACRNAME --query "loginServer" --output tsv)
DOCKERIMAGE_ID=$(docker images -q "$DOCKERIMAGE_NAME:$DOCKERIMAGE_TAG_VERSION")
if [ -z "$DOCKERIMAGE_ID" ]; then
    echo "Docker image '$DOCKERIMAGE_NAME' not found. Let us create it"
else
    echo "There is a docker image with id $DOCKERIMAGE_ID, let us remove it first"
    docker rmi -f $DOCKERIMAGE_ID
fi
docker build -t $DOCKERIMAGE_NAME:$DOCKERIMAGE_TAG_VERSION .
DOCKERIMAGE_ID=$(docker images -q "$DOCKERIMAGE_NAME:$DOCKERIMAGE_TAG_VERSION")
docker tag $DOCKERIMAGE_ID $DOCKERHUBURL/$DOCKERIMAGE_NAME:$DOCKERIMAGE_TAG_VERSION
docker push $DOCKERHUBURL/$DOCKERIMAGE_NAME:$DOCKERIMAGE_TAG_VERSION

#################DEPLOY PYTHON APP ON AZURE AKS CLUSTER########################
echo "Let Us Conigure Kubeconfig and update for AKS"
[ -d $AGENT_WORKFOLDER/.kube ] && {
  echo "There is already Kubeconfig folder. Let us just update config"
} || {
  echo "There is no Kubeconfig folder. Let us create it and update config"
  mkdir $AGENT_WORKFOLDER/.kube
}
export KUBECONFIG=$AGENT_WORKFOLDER/.kube/config
az aks get-credentials --resource-group $AKSRESOURCEGROUP --name $AKSNAME --overwrite
DOCKERHUBURL=$(az acr show --name $AZUREACRNAME --query "loginServer" --output tsv)
export IMAGE_NAME=$DOCKERHUBURL/$DOCKERIMAGE_NAME:$DOCKERIMAGE_TAG_VERSION
echo "LET US LOOK AT IMAGE NAME : $IMAGE_NAME"
PODS=$(kubectl get pods -n $NAMESPACE -l app=$DEPLOYMENT_NAME -o custom-columns=NAME:.metadata.name --no-headers)
if [ -z "$PODS" ]; then
    echo "There is no $DEPLOYMENT_NAME deployment. Let us create it"
    envsubst < azureaks.yaml | kubectl apply -f -
    envsubst < cert-request.yaml | kubectl apply -f -
    kubectl get pods
else
    echo "There is already pods with name $PODS let us update deployment"
    NEW_REPLICA=$((DEPLOYMENTREPLICA + 1))
    kubectl scale deployment/$DEPLOYMENT_NAME --replicas=$NEW_REPLICA
    kubectl get pods
    kubectl wait deployment/$DEPLOYMENT_NAME --for=condition=Available --timeout=120s
    echo Deleting pods: $PODS
    kubectl delete pod $PODS -n $NAMESPACE
    kubectl scale deployment/$DEPLOYMENT_NAME --replicas=$DEPLOYMENTREPLICA
    kubectl get pods
fi