#!/bin/sh
# shellcheck disable=SC2154

export HOME=/plugin

env > /tmp/"${ARGOCD_APP_NAME}".env

echo "${ARGOCD_APP_PARAMETERS}" | jq '.[] | select(.name == "helm-parameters") | .map' | yq -P -oy > parameters.yaml
cp parameters.yaml /tmp/"${ARGOCD_APP_NAME}"-parameters.yaml

if [ -n "${PARAM_CHART}" ] && [ "${PARAM_CHART}" != "." ]; then
    CHART=${PARAM_CHART}
elif [ -d chart ]; then
    CHART=chart
elif [ -f chart ]; then
    CHART=$(cat chart)
else
    CHART="."
fi

[ -f chart/values.yaml ] && VALUES="-f chart/values.yaml"
[ -f values-chart.yaml ] && VALUES="${VALUES} -f values-chart.yaml"
[ -f values.yaml ] && VALUES="${VALUES} -f values.yaml"
[ -f values-"${PARAM_ENV}".yaml ] && VALUES="${VALUES} -f values-${PARAM_ENV}.yaml"
VALUES="${VALUES} -f parameters.yaml"

helm dependency update "${CHART}" >/tmp/"${ARGOCD_APP_NAME}"-helm-dependency-build.out

mkdir -p base
echo "helm template -n ${ARGOCD_APP_NAMESPACE} ${PARAM_FLAGS} ${VALUES} ${ARGOCD_APP_NAME} ${CHART}" > /tmp/"${ARGOCD_APP_NAME}"-helm.sh
helm template -n "${ARGOCD_APP_NAMESPACE}" "${PARAM_FLAGS}" "${VALUES}" "${ARGOCD_APP_NAME}" "${CHART}" > ./base/_manifest.yaml

cp ./base/_manifest.yaml /tmp/"${ARGOCD_APP_NAME}"-manifest.yaml

[ -d "${PARAM_ENV}" ] && kubectl kustomize "${PARAM_ENV}" > /tmp/"${ARGOCD_APP_NAME}"-manifest.yaml

cat /tmp/"${ARGOCD_APP_NAME}"-manifest.yaml
