#!/bin/bash
echo "#lint all helm charts - $0"

      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

      if [[ $( sops -version | 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

  echo "#$fn: helm version --client"
  helm version --client
  if [[ -z "$WORKINGDIR" ]];
  then
    WORKINGDIR=/home/pieter/git
    echo "Empty var \$WORKINGDIR set to local dir for debug"
  fi
  echo "pwd=${PWD}  WORKINGDIR=$WORKINGDIR "
  ( set -x ; ls -l $WORKINGDIR )

[[ -z "${AGENT_TEMPDIRECTORY}" ]] && AGENT_TEMPDIRECTORY="/tmp"
#helm dir and chart must match for lint.
mkdir -p ${AGENT_TEMPDIRECTORY}/helmchart
cp -a * ${AGENT_TEMPDIRECTORY}/helmchart/ && false


# az login with service principal, to decrypt sops secrets.yaml
echo "#####$fn: az login --service-principal --username $SP_DEPLOY_ID --password $SP_DEPLOY_SECRET --tenant $TENANT"
echo "2020-05-29 Azure pipeline bug, mapping secret var into environment."
echo "SPDEBUG=\"$SPDEBUG\"  SPDEBUGB=\"$SPDEBUG\" SP_DEPLOY_SECRET=\"$SP_DEPLOY_SECRET\" "
if [[ -z "$SP_DEPLOY_ID" ]];
then
    echo "Skip login \$SP_DEPLOY_ID is empty."
else
    set -x
    az login  --service-principal \
          --username $SP_DEPLOY_ID \
          --password $SPDEBUG \
          --tenant $TENANT
fi

echo "#$fn: Start lint loop ...  AGENT_TEMPDIRECTORY=${AGENT_TEMPDIRECTORY}"
#Exit on error
set -ex
for valuesfile in `find ${AGENT_TEMPDIRECTORY}/helmchart/env -name values.yaml | grep -v "removed-env"`
do
  #Strip values.yaml to create secrets.yaml with path.
  secretsfile="${valuesfile::-12}/secrets.yaml"
  echo "##   Helm lint -f \"${valuesfile}\"  -f \"${secretsfile}\" ..."
  helm secrets lint ${AGENT_TEMPDIRECTORY}/helmchart \
    -f ${AGENT_TEMPDIRECTORY}/helmchart/secrets.yaml \
    -f ${valuesfile} \
    -f ${secretsfile} \
    -f ${WORKINGDIR}/manifest/artifacts.yaml &
  echo "------------------------------"
done

echo "Done."
