#!/bin/bash
# This script will install correct helm version.
# after cluster creation and setting of kubectl context

# 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 HELMVERSION AKSCLUSTERNAME;
do
  if [ -z "${!resource}" ]; then
    echo "####$fn: $resource Not found. Check pipeline variables"
    exit 1;
  fi
done




currentHelmVersion=$( helm version --client --short 2>&1 | grep "^v")
echo "####$fn: currentHelmVersion=\"$currentHelmVersion\"  ,HELMVERSION=\"$HELMVERSION\""
if [[ "$currentHelmVersion" =~ $HELMVERSION ]] ; then
  echo "####$fn: helm verion matches requested version, nothing more to do"
else
  ls -lh
  echo "####$fn: Download and install helm HELMVERSION=$HELMVERSION"
  if [[ $HELMVERSION =~ ^v2.*$ ]]; then
    echo "####$fn: curl download old v2 get_helm2.sh and run ... HELMVERSION=\"$HELMVERSION\""
    output=$( curl -sS -L -o get_helm2.sh https://raw.githubusercontent.com/kubernetes/helm/master/scripts/get 2>&1)
    rc=$?; if [[ $rc -ne 0 ]]; then echo "####$fn: ERROR: helm2 curl get_helm.sh "; echo "$output"; exit $rc; fi
    helmv=2
  else
    echo "####$fn: curl download new v3 get_helm3.sh and run ... HELMVERSION=\"$HELMVERSION\""
    output=$( curl -sS -L -o get_helm3.sh https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 2>&1)
    rc=$?
    if [[ $rc -ne 0 ]]; then
        echo "####$fn: ERROR: helm3 curl get_helm3.sh "; echo "$output"; exit $rc
    else
        echo "####$fn: got helm3 download script .."
    fi
    helmv=3
  fi
  chmod +x get_helm${helmv}.sh

  output="empty"
  if [[ "$HELMVERSION" == "" ]] || [[ "$HELMVERSION" == "v2" ]] || [[ "$HELMVERSION" == "v3" ]]; then
    echo "####$fn: [helmv=$helmv] ./get_helm${helmv}.sh   (No specific version)"
    ./get_helm${helmv}.sh --no-sudo
  else
    if [[ $helmv -eq 2 ]]; then
      #2020-05-27 v2 helm install failed in bac-uat cp: cannot create regular file '/usr/local/bin/tiller': Permission denied
      echo "####$fn: [helmv=$helmv] ./get_helm2.sh --version $HELMVERSION "
      ./get_helm2.sh --no-sudo --version ${HELMVERSION}
    else
      echo "####$fn: [helmv=$helmv] ./get_helm3.sh --no-sudo --version $HELMVERSION "
      ./get_helm3.sh --no-sudo --version ${HELMVERSION}
    fi
  fi
  rc=$?
  if [[ $rc -ne 0 ]]; then
    echo "####$fn: ERROR: sh ./get_helm$helmv.sh , HELMVERSION=\"$HELMVERSION\"."
    ls -lh get_helm${helmv}.sh
    echo
    id
    pwd
    exit $rc
  fi
fi

##Helm done now for secrets , sops, tillerless

if [[ $helmv -eq 3 ]]; then
    if [[ ! $( helm plugin list | grep secrets ) ]]; then
        echo "#$fn: install helm secrets plugin as it is missing ..."
        helm plugin install https://github.com/futuresimple/helm-secrets
    fi
    # helm plugin install installs sops 3.0.3 as of 2020-05-28 upgrade to azure sops >= 3.5
    if [[ $( sops -version 2>&1  | grep "sops 3.0\|sops: command not found" ) ]]; then
        echo "#$fn: upgrade sops encryption to 3.5.0 ..."
        curl -SsL  https://github.com/mozilla/sops/releases/download/v3.5.0/sops_3.5.0_amd64.deb -o "$WORKINGDIR/sops_3.5.0_amd64.deb"
        sudo dpkg -i $WORKINGDIR/sops_3.5.0_amd64.deb
    fi
    echo "#$fn: helm3 plugin list"
    helm plugin list
    echo "#$fn: sops -version"
    sops -version
fi


#Use tilerless helm2 or helm3
HELMLOCAL=true
if [[ "$helmv" = "2" ]] ; then
  ## 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
  echo '#$fn: Using Tillerless Helm plugin'
  export HELM_TILLER_HISTORY_MAX=3;
  helm init --client-only
  helm plugin install https://github.com/rimusz/helm-tiller
  helm tiller start-ci
  export HELM_HOST=127.0.0.1:44134
fi



(set -x ; helm version --client )
# if [[ "$HELMLOCAL" = true ]] && [[ "$helmv" = "2" ]] ; then
#   echo "####$fn: helm2 tiller stop"
# 	helm tiller stop
# fi
