#!/bin/bash
__SUMMARY__=$(cat <<"__TLDR__"
test-helm-chart: builds a helm chart and tests it with some values
__TLDR__
)

export PS4='+ ${FUNCNAME:-(main)}:${LINENO}: '

Prog=${0##*/}

fail () {
    set +o nounset
    ret=${1:-1}
    shift &>/dev/null || :
    if [[ -z $* ]]; then
        echo "$Prog: unspecified failure, exiting" >&2
    else
        echo "$Prog:" "$@" >&2
    fi
    exit "$ret"
}

realpath () {
    python3 -c 'import sys, os; print(os.path.realpath(sys.argv[1]))' "$1"
}

usage () {
    echo >&2 "$__SUMMARY__"
    echo >&2
    echo >&2 "Usage: $Prog <chart dir> [<values file>] [<instance name>]"
    exit "$1"
}

require_program () {
    command -v "$1" &>/dev/null ||
        fail 127 "Required program '$1' not found in PATH"
}

if [[ $1 == -h || $1 == --help ]]; then
    usage 0
fi

set -o nounset
IFS=$'\n\t'
unset GREP_OPTIONS POSIXLY_CORRECT

require_program helm


if [[ $# -ne 1 && $# -ne 2 && $# -ne 3 ]]; then
    usage 2
fi

Chart_dir=$(realpath "$1")
Values_file=${2:-$Chart_dir/values.yaml}
Instance=${3:-test-helm-chart}

[[ -d $Chart_dir ]] || fail 1 "Invalid chart dir $Chart_dir: not a directory"
[[ -f $Chart_dir/Chart.yaml ]] || fail 1 "Invalid chart dir $Chart_dir: Chart.yaml missing"
[[ -f $Values_file ]] || fail 1 "Values file $Values_file missing"

out=$(helm package "$Chart_dir"); ret=$?
if [[ $ret != 0 ]]; then
    fail 3 "Helm package failed with code $ret; output: $out"
fi
if [[ $out =~ Successfully\ packaged\ chart.*:\ (.*\.tgz) ]]; then
    Chartball=${BASH_REMATCH[1]}
else
    fail 3 "Couldn't get tarball name from 'helm package' output"
fi
# Chart_name=$(basename "$Chart_dir")
# Chartball="${Chart_name}.tar.gz"

# tar --exclude-backups --exclude='.*.sw[po]' -C "$Chart_dir/.." -czf "$Chartball" "$Chart_name" || fail 3 "Failed to create $Chartball"
if [[ -t 1 ]]; then
    Pager=less
else
    Pager="cat"
fi

set -o pipefail
helm template --debug "$Instance" "$Chartball" -f "$Values_file" 2>&1 | $Pager


# vim:et:sw=4:sts=4:ts=8
