#!/bin/bash
set -e

# Helm chart inflator

# Reads a file like this
#
#  apiVersion: kustomize.config.k8s.io/v1
#  kind: ChartInflatorExec
#  metadata:
#    name: notImportantHere
#  chart: chartName
#  values: /absolute/path/to/values/file
#  helmBin: /absolute/path/to/helmBin
#
# fetches the given chart from stable/$chartName,
# and inflates it to stdout, using the given values file.
#
# Example execution:
# ./plugins/kustomize.config.k8s.io/v1/ChartInflatorExec configFile.yaml



# Yaml parsing is a ridiculous thing to do in bash,
# but let's try:
function parseYaml {
  local file=$1
  while read -r line
  do
    local k=${line%:*}
    local v=${line#*:}

    [ "$k" == "chart" ] && chartName=$v
    [ "$k" == "values" ] && valuesFile=$v
    [ "$k" == "helmBin" ] && helmBin=$v
  done <"$file"

  # Trim leading space
  chartName="${chartName#"${chartName%%[![:space:]]*}"}"
  valuesFile="${valuesFile#"${valuesFile%%[![:space:]]*}"}"
  helmBin="${helmBin#"${helmBin%%[![:space:]]*}"}"
}

TMP_DIR=$(mktemp -d)

# Where all the files generated by 'helm init' live.
HELM_HOME=$TMP_DIR/dotHelm

# Where helm charts are unpacked.
CHART_HOME=$TMP_DIR/charts

parseYaml $1

if [ -z "$helmBin" ]; then
  helmBin=/usr/local/bin/helm
fi

if [ -z "$valuesFile" ]; then
  valuesFile=$CHART_HOME/$chartName/values.yaml
fi

function doHelm {
  $helmBin --home $HELM_HOME $@
}

# The init command is extremely chatty
doHelm init --client-only >& /dev/null

doHelm fetch --untar \
    --untardir $CHART_HOME \
    stable/$chartName

doHelm template \
    --values $valuesFile \
    $CHART_HOME/$chartName

/bin/rm -rf $TMP_DIR
