
#!/bin/bash
fn=`basename "$0"`
echo "#$fn: Running helm Install or Upgrade"

# set -x

#echo "#$fn: Check required environment variables"
#printenv | grep 'workingDir\|en\|ch'

## Azure DROP dir
#  add Drop/drop before we read config file, allow override.
WORKINGDIR="$WORKINGDIR"  ##This was passed to us.
if [[ ! -d "$WORKINGDIR" ]]; then
  WORKINGDIR=$SYSTEM_ARTIFACTSDIRECTORY
  echo "#$fn: using SYSTEM_ARTIFACTSDIRECTORY as WORKINGDIR=$WORKINGDIR"
fi

# 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}

if [ -f "$2" ]; then #Local debug credentials in 2nd file not in git
  echo "#$fn: !!!## 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

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

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

echo "#$fn: check given aks cluster $ az aks show --name $AKSCLUSTERNAME --resource-group $aksResourceGroup --output table"
aks_cluster_status=$(az aks show --name $AKSCLUSTERNAME --resource-group $aksResourceGroup --output table)
echo "$aks_cluster_status"

echo "$aks_cluster_status" | grep "^$AKSCLUSTERNAME" | grep -o "Succeeded"
rc=$?
if [ $rc -eq 0 ]; then
  echo "#$fn: $AKSCLUSTERNAME Cluster already exsist in RG $aksResourceGroup"

  echo "#$fn: check kubectl context  (az aks get-credentials --resource-group $aksResourceGroup --name $AKSCLUSTERNAME)"
  # az aks get-credentials  --resource-group $aksResourceGroup \
  #                         --name $AKSCLUSTERNAME \
  #                         --overwrite-existing
  ## make sure kubectl context is set before running tiller.
  context=$(kubectl config current-context )
  if [[ "$context" != "$AKSCLUSTERNAME" ]]; then
    echo "####$fn: ERR the current kubectl context not AKSCLUSTERNAME=$AKSCLUSTERNAME , it is $context"
    exit 1
  fi

  kubConfigPath=$(ls $HOME/.kube/config)
  nameSpace=$CH-$AKSENVIRONMENT
  # timeout in seconds 600 = 10min , 1800=30min
  maxTimeOut=1800

  # check the namespace and if not create namespace
  kubectl get ns | grep -o "$nameSpace"
  rc=$?
  if [[ $rc != 0 ]]; then
      echo "#$fn: could not find namespace $nameSpace, creating it now ..."
      kubectl create ns "$nameSpace"
      kubectl get ns | grep -o "$nameSpace"
      rc=$?
      if [[ $rc != 0 ]]; then
          echo "#$fn: Error after creating namespace $nameSpace still cant find it."
          exit 1
      fi
  fi
  echo "#$fn: confirmed we have namespace \"$nameSpace\""
  kubectl config set-context $(kubectl config current-context) --namespace=$nameSpace


  #202007 Set injected values prefixed with HELM_<>
  echo "#$fn: find HELM_SET env var"
  helmset=""
  # Azure only pass env vars as uppercase  HELM_SET<02> = "setDeploymentsEnabled=false"
  for v in ${!HELM_SET*} ; do
    echo "#$fn:  found env \"$v\"  # add --set ${!v}   to be passed to helm deploy"
    printf -v helmset '%s --set %s' "$helmset" "${!v}"
  done
  echo

  echo "#$fn: Printing required variables"
  echo "    WORKINGDIR=$WORKINGDIR"
  echo "    SYSTEM_ARTIFACTSDIRECTORY=$SYSTEM_ARTIFACTSDIRECTORY"
  echo "    RELEASE_PRIMARYARTIFACTSOURCEALIAS=$RELEASE_PRIMARYARTIFACTSOURCEALIAS"
  echo "    AKSENVIRONMENT=$AKSENVIRONMENT"
  echo "    CH=$CH"
  echo "    CHANNEL=$CHANNEL"
  echo "    kubConfigPath=$kubConfigPath"
  echo "    nameSpace=$nameSpace"
  echo "    helmset=$helmset"

  #In old v1 ocb was in dir /env/ocbc/   ch=ocb, channel=ocbc
  channel=${CHANNEL:=$CH}
  echo "    set channel=$channel    /env/$channel/$AKSENVIRONMENT/(values|secrets).yaml"

  chartPath=$WORKINGDIR/helmchart
  valuesYamlFile=$chartPath/env/$channel/$AKSENVIRONMENT/values.yaml
  secretsYamlFile=$chartPath/env/$channel/$AKSENVIRONMENT/secrets.yaml
  valueArtifactsFile=$WORKINGDIR/Drop/drop/build.manifest/artifacts.yaml
  if [[ -f "$valueArtifactsFile" ]]; then
    echo "#$fn: found $valueArtifactsFile "
  else
    valueArtifactsFile=$WORKINGDIR/$RELEASE_PRIMARYARTIFACTSOURCEALIAS/drop/build.manifest/artifacts.yaml
    if [[ -f "$valueArtifactsFile" ]]; then
      echo "#$fn: found $valueArtifactsFile , had to look in RELEASE_PRIMARYARTIFACTSOURCEALIAS=$RELEASE_PRIMARYARTIFACTSOURCEALIAS"
    else
      #Last resort check for local test artifacts in git repo
      valueArtifactsFile=~/git/build.manifest/artifacts.yaml
      if [[ -f "$valueArtifactsFile" ]]; then
        echo "#$fn: found $valueArtifactsFile , LOCAL test ??"
      else
        echo "#$fn: missing drop/build.manifest/artifacts.yaml !!!"
        ( set -x ; ls -l $WORKINGDIR )
        exit 1
      fi
    fi
  fi

  HELMLOCAL=true
  currentHelmVersion=$( helm version --client --short 2>&1 | grep "^v")
  rc=$?; if [[ $rc -ne 0 ]]; then echo "####$fn: ERROR getting helm version ???" ; exit $rc; fi
  if [[ "$currentHelmVersion" =~ "v2\." ]] ; then
    helmv=2
  else
    helmv=3
  fi
  echo "####$fn: Helm$helmv   currentHelmVersion=$currentHelmVersion"


  if [ "$helmv" = "2" ] ; then
      #helm_client_version=$(helm version --client| awk -F'"' '{print $2}')
      #echo helm version is $helm_client_version
      echo "#$fn: using helm2 with no tiller in cluster"
      export HELM_TILLER_HISTORY_MAX=3;
      # helm tiller start-ci
      # export HELM_HOST=127.0.0.1:44134
      # echo "#$fn: helm2 upgrade --namespace $nameSpace ..."
      helm upgrade  --namespace $nameSpace \
                    --install \
                    --values $valueArtifactsFile \
                    -f $valuesYamlFile $nameSpace $chartPath \
                    --timeout $maxTimeOut \
                    --tiller-connection-timeout $maxTimeOut \
                    --kubeconfig $kubConfigPath
      rc=$?
      if [[ $rc == 0 ]];
      then
        echo "#$fn: Helm2 --namespace $nameSpace upgrade completed successfully"
      else
        echo "#$fn: Error on Helm2 upgrade --namespace $nameSpace !!!!"
        exit 1
      fi
      echo "#$fn: helm2 tiller stop"
      helm tiller stop
      exit 0
  else
      echo
      echo "#$fn: helm${helmv} secrets upgrade  --namespace $nameSpace ... $helmset"
      # Usage:  helm upgrade [RELEASE] [CHART] [flags]
      set -x
     # helm secrets upgrade --install \
      #    --namespace $nameSpace \
       #   --values $valueArtifactsFile \
       #   -f $chartPath/secrets.yaml \
       #   -f $valuesYamlFile \
       #   -f $secretsYamlFile \
       #   --timeout ${maxTimeOut}s \
      #    --kubeconfig $kubConfigPath \
       #   --force --atomic \
       #   $helmset $nameSpace $chartPath
      ## --force >> force resource updates through a replacement strategy
      #rc=$?
      #if [[ $rc != 0 ]]; then
       # echo
       # echo "#$fn: FAILED: helm${helmv} secrets upgrade , try with NO --force .... $helmset"
        helm secrets upgrade --install \
          --namespace $nameSpace \
          --values $valueArtifactsFile \
          -f $chartPath/secrets.yaml \
          -f $valuesYamlFile \
          -f $secretsYamlFile \
          --timeout ${maxTimeOut}s \
          --history-max 1 \
          --kubeconfig $kubConfigPath \
          $helmset $nameSpace $chartPath
        rc=$?
      #fi
      set +x
      if [[ $rc == 0 ]];
      then
        echo "#$fn: Helm${helmv} --namespace $nameSpace upgrade completed successfully"
      else
        echo "#$fn: Error on Helm${helmv} upgrade --namespace $nameSpace !!!!"
        exit 1
      fi
      exit 0
  fi


else
    echo "$fn: Cluster not found "
    exit 1
fi

