#! /bin/bash

set -eo pipefail

# by default - test files generated by "helm template" will be skipped
helm_options=(--skip-tests)

datree_options=()
helm_chart_location=""
helm_chart_name=""
datree_command=""
eoo=0

helm_command=${DATREE_HELM_COMMAND:-helm}

while [[ $1 ]]; do
    if ! ((eoo)); then
        if [[ $1 == "--include-tests" ]]; then
            helm_options=()
        elif [[ $1 == "--" ]]; then
            eoo=1
        elif [[ $helm_chart_location == "" && $($helm_command show chart $1 2> /dev/null | grep apiVersion) == apiVersion* ]]; then
            helm_chart_location=$1
            helm_chart_name=$($helm_command show chart $1 | grep -o '^name: .*' | cut -c 7-)
        else
            datree_options+=("$1")
        fi

        shift
    else
        helm_options+=("$1")
        shift
    fi
done

if [[ ${helm_chart_location} != "" ]]; then
    currUinxTimestamp=$(date +%s)
    tempManifestPath="/tmp/helmtmp-${helm_chart_name}_$currUinxTimestamp.yaml"
    $helm_command template "${helm_options[@]}" "$helm_chart_location" > $tempManifestPath
    if [ -s $tempManifestPath ]; then
        $HELM_PLUGIN_DIR/bin/datree "${datree_options[@]}" $tempManifestPath
    else
        helm template "${helm_options[@]}" "$helm_chart_location" | $HELM_PLUGIN_DIR/bin/datree "${datree_options[@]}" -
    fi
else
    $HELM_PLUGIN_DIR/bin/datree "${datree_options[@]}"
fi
