#!/bin/bash

# set -x
# printenv

# passing configuration file eg : create_aks_cluster.sh bnz-uat.conf | create_aks_cluster.sh bnz-prd.conf | 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 with service principal --username $SP_DEPLOY_ID --tenant $TENANT"
    az login  --service-principal \
              --username $SP_DEPLOY_ID \
              --password $SP_DEPLOY_SECRET \
              --tenant $TENANT
    # set subscription
    echo "#$fn: az account set --subscription $SUBSCRIPTIONID"
    az account set --subscription $SUBSCRIPTIONID
    #az account list --output table
  fi
fi

#Check if Azure Keyfault set, if not skip all of copy to secrets, now handeld by helm secrets.yaml 202007
if [[ ! -z "$AKVNAME" ]]; then
    # check the resouces availability from az pipeline
    for resource in AKSCLUSTERNAME TENANT SUBSCRIPTIONID AKSENVIRONMENT CH;
    do
      if [ -z "${!resource}" ]; then
        echo "$resource Not found. Check pipeline variables"
        exit 1;
      fi
    done

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

    # check given aks cluster has been created
    aks_cluster_status=$(az aks show --name $AKSCLUSTERNAME --resource-group $aksResourceGroup --output table)
    echo "$aks_cluster_status" | grep "^$AKSCLUSTERNAME" | grep -o "Succeeded"
    rc=$?

    if [[ $rc == 0 ]]; then
      echo "#$fn: $AKSCLUSTERNAME Cluster already exsist on RC $aksResourceGroup"

      ## kubectl context should be set by create_aks_cluster step

      # check able to see the cluster
      az aks show --name $AKSCLUSTERNAME --resource-group $aksResourceGroup --query name --output tsv | grep -o $AKSCLUSTERNAME
      rc=$?; if [[ $rc != 0 ]]; then echo "#$fn: aks $AKSCLUSTERNAME not able to access cluster"; exit $rc; fi

      # set contexts to $AKSCLUSTERNAME
      currentContext=$(kubectl config  current-context)
      if [ "$currentContext" != "$AKSCLUSTERNAME" ]; then kubectl config use-context $AKSCLUSTERNAME; fi
      rc=$?; if [[ $rc != 0 ]]; then echo "#$fn: not able to set the context to $AKSCLUSTERNAME"; exit $rc; fi

      # check the namespace and if not create namespace
      nameSpace=$CH-$AKSENVIRONMENT
      kubectl get ns | grep -o "$nameSpace"
      rc=$?
      if [[ $rc != 0 ]]; then kubectl create ns "$nameSpace"; fi
      kubectl get ns | grep -o "$nameSpace"
      rc=$?
      if [[ $rc != 0 ]]; then echo "#$fn: Error creating namespace $nameSpace"; exit 1; fi

      # set as defaut namespace
      kubectl config set-context $(kubectl config current-context) --namespace=$nameSpace

      # match and select correct kv
      # check the pipeline variable
      if [[ -z "$AKVNAME" ]]; then
        echo "#$fn:  keyvault not specified try name==$nameSpace for matching keyvault"
        AKVNAME=$(az keyvault list --query "[?name=='$nameSpace'].name" -o tsv)
        # check for the environment keyvault
        if [[ -z "$AKVNAME" ]]; then
          echo "#$fn:  keyvault not found now try any name that contains \"all-$AKSENVIRONMENT\" "
          AKVNAME=$(az keyvault list --query "[?contains(name,'all-$AKSENVIRONMENT')].name" -o tsv)
        # if still empty set error
          if [ -z "$AKVNAME" ]; then
            echo
            echo "#$fn: WARNING: Can't find the correct keyvault. exiting"
            echo "#$fn: assume all secrets moved to helm. secrets.yaml"
            #exit 1;
            echo
            exit 0
          fi
        fi
      else
        AKVNAME=$AKVNAME
      fi
      echo "#$fn: Azure keyvault to use : $AKVNAME"

      #
      # Got keyvault now extract certs and secrets
      #

      certNames=()
      # list all certificates starting with "/kv-"
      certNames+=( $(az keyvault certificate list --vault-name $AKVNAME --query "[?contains(id,'/kv-') && attributes.enabled].id" -o tsv |\
                    awk -F'/certificates/' '{print $2}'|\
                    grep "^kv-$CH-$AKSENVIRONMENT-\|^kv-$CH-all-\|^kv-all-$AKSENVIRONMENT\|^kv-all-all") )
      rc=$?; if [ $rc -ne 0 ]; then
          echo
          echo "#$fn: ERROR: Can't find certificates, starting with kv- in keyvault $AKVNAME  CH=$CH AKSENVIRONMENT=$AKSENVIRONMENT";
          echo "#$fn: moved secrets to helm secrets.yaml, assume kv deleted.",
          echo
          exit 0;
        fi

      # check array is empty
      if [ ! "${#certNames}" ]; then echo "$fn: Error !!! Double check keyvault certificates, start with kv-$CH-$AKSENVIRONMENT in keyvault $AKVNAME"; exit 1; fi

      echo "#$fn: cert names: ${certNames[@]}"

      for certName in "${certNames[@]}";
      do
        # remove old files
        rm -f /tmp/$certName-cert.pem /tmp/$certName-privateKey.pem
        echo "#$fn: download certs and pvt key for --name $certName from --vault-name $AKVNAME"
        ## We got certificate name but to get CA and pvt key we download the secret for the cert. task10790
        # az keyvault certificate download  --name $certName \
        #                                   --vault-name $AKVNAME \
        #                                   --file /tmp/$certName-cert.pem
        az keyvault secret download --name $certName \
                                    --vault-name $AKVNAME \
                                    --file /tmp/$certName-privateKey.pem


        # run python script to split stacked pem into .key and certs .pem
        # 202004 only python3.5 on deployment, used docker to get python 3.6 for fstring
        #$path_dir/az_script-30helper-split-pem.py /tmp/$certName-privateKey.pem /tmp/$certName-split
        echo "#$fn: docker run az_script-30helper-split-pem.py  /tmp/$certName-privateKey.pem /tmp/$certName-split"
        docker run --rm --name az_script-30helper-split-pem.py \
            -v "$path_dir":/app -w /app \
            -v /tmp:/tmp \
            --env certName=$certName \
            --env USER_ID=$(id -u ${USER}) \
            --env GROUP_ID=$(id -g ${USER}) \
            python:3.7-alpine \
                sh -c 'python -m pip install pem ; python az_script-30helper-split-pem.py /tmp/$certName-privateKey.pem /tmp/$certName-split ; chown --changes --silent ${USER_ID}:${GROUP_ID} /tmp/$certName-split* '

        rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi

        checkDate='15 days'
        echo "#$fn: check cert validity for $checkDate on $certName-split.pem"
        openssl x509 -in /tmp/$certName-split.pem -text -noout | grep -A 2 'Validity'

        validity=$(openssl x509 -in /tmp/$certName-split.pem -text -noout | grep 'Not After' | awk -F'Not After :' '{print $2}' |sed 's/^ *//g')
        epochDateValid=$(date --date "$validity" +'%s')
        epochDatecheck=$(date --date "$checkDate" +'%s')

        if [ "$epochDateValid" -lt "$epochDatecheck" ]; then  echo "#$fn: Trying to use certificate about to expire or expired. Throw error"; exit 1; fi

        echo "#$fn: kubectl create secret tls $certName"
        kubectl create secret tls $certName --key  /tmp/$certName-split.key \
                                            --cert /tmp/$certName-split.pem \
                                            -n $nameSpace
        rc=$?;

        if [[ $rc != 0 ]]; then
          echo "#$fn: In $nameSpace, $certName already exist. Removing and re-adding";
          kubectl delete secret $certName -n $nameSpace
          rc=$?;
          if [[ $rc == 0 ]]; then
            kubectl create secret tls $certName --key  /tmp/$certName-split.key \
                                                --cert /tmp/$certName-split.pem \
                                                -n $nameSpace
            rc=$?; if [[ $rc == 0 ]]; then echo "#$fn: In $nameSpace, $certName has been created/updated"; fi
          else
            echo "#$fn: In $nameSpace, $certName  error deleting"
            rm -f /tmp/$certName-* || true
            exit $rc;
          fi
        else
          echo "#$fn: In $nameSpace, $certName has been created for the 1st time";
        fi

        rm -f /tmp/$certName-* || true

        echo "#$fn: list k8s secrets ..."
        kubectl -n $nameSpace get secrets | grep -o $certName
        rc=$?; if [[ $rc != 0 ]]; then echo "#$fn: In $nameSpace, $certName cant find"; exit $rc; fi

        echo "#$fn: cleanup remove secrets, and split files"
        rm -f /tmp/$certName-cert.pem /tmp/$certName-privateKey.pem /tmp/$certName-split.key /tmp/$certName-split.pem || true
      done


      # list all secret's (Not certificates)
      secretNames=()
      secretNames+=( $( az keyvault secret list --vault-name $AKVNAME --query "[?contains(id,'/kv-') && attributes.enabled && contentType!='application/x-pem-file'].id" -o tsv |\
                        awk -F'/secrets/' '{print $2}' |\
                        grep "^kv-$CH-$AKSENVIRONMENT-\|^kv-$CH-all-\|^kv-all-$AKSENVIRONMENT\|^kv-all-all" )
                    )
      rc=$?; if [[ $rc != 0 ]]; then echo "#$fn: Can't find secrets, start with kv-"; exit 1; fi

      # check array is empty
      if [ ! "${#secretNames}" ]; then echo "#$fn: Error !!! Double check keyvault secrets, start with kv-$CH-$AKSENVIRONMENT"; exit 1; fi

      echo "#$fn: Printing all secret names ${secretNames[@]}"

      for secretName in "${secretNames[@]}";
      do
        # remove old files
        rm -f /tmp/$secretName
        # download secrets
        az keyvault secret download --name $secretName --vault-name $AKVNAME --file /tmp/$secretName

        # add secrets
        kubectl create secret generic $secretName --from-file=/tmp/$secretName -n $nameSpace
        rc=$?;

        # if exsist re-adding
        if [[ $rc != 0 ]]; then
          echo "#$fn: In $nameSpace, $secretName already exist. Removing and re-adding";
          kubectl delete secret $secretName -n $nameSpace
          rc=$?;
          if [[ $rc == 0 ]]; then
            kubectl create secret generic $secretName --from-file=/tmp/$secretName -n $nameSpace
            rc=$?; if [[ $rc == 0 ]]; then echo "#$fn: In $nameSpace, $secretName has been created/updated"; fi
          else
            echo "#$fn: In $nameSpace, $secretName  error deleting"
            exit $rc;
          fi
        else
          echo "#$fn: In $nameSpace, $secretName has been created for the 1st time";
        fi

        kubectl -n $nameSpace get secrets | grep -o $secretName
        rc=$?; if [[ $rc != 0 ]]; then echo "#$fn: In $nameSpace, $secretName cant find"; exit $rc; fi

      done

    else
      echo "#$fn: Cluster not found "
    fi
else
echo "#$fn: Empty AKVNAME, skip secret copy from keyvault, probably handled by helm secrets.yaml now."
fi

