#!/usr/bin/env bash
# shellcheck disable=SC2034  # Unused variables left for readability

helmfile () {

name=$1
tier=$2

cat <<EOF
bases:
 - ../envs/environments.yaml.gotmpl

commonLabels:
  tier: ${tier}

releases:
- name: ${name}
  namespace: {{ .Environment.Name }}-${name}
  chart: ../charts/${name}
  condition: ${name}.enabled
  values:
  - ../values/${name}/values/values.yaml.gotmpl
  - ../values/${name}/values/values-{{ .Environment.Name }}.yaml
  postRenderer: ../bin/kustomizer
  postRendererArgs:
  - ../values/${name}/kustomize/{{ .Environment.Name }}
  missingFileHandler: Info
- name: manifests
  namespace: {{ .Environment.Name }}-${name}
  chart: manifests
  condition: ${name}.enabled
  missingFileHandler: Info
  values:
  - ../values/env.yaml
  - ../values/env-{{ requiredEnv "ARGOCD_ENV_CLUSTER_NAME" }}.yaml
  - ../values/${name}/env.yaml.gotmpl
  - ../values/${name}/env-{{ requiredEnv "ARGOCD_ENV_CLUSTER_NAME" }}.yaml.gotmpl
  hooks:
  - events: [ prepare, cleanup ]
    showlogs: true
    command: ../bin/helmify
    args:
    - '{{\`{{ if eq .Event.Name "prepare" }}build{{ else }}clean{{ end }}\`}}'
    - '{{\`{{ .Release.Chart }}\`}}'
    - '{{\`{{ .Environment.Name }}\`}}'
    - ../values/${name}/manifests
    - manifests
EOF
}

while true; do
    case $* in
        --with-env)
            ns=true
            shift ;;
        --*|-*) shift;;
        *) break ;;
    esac
done

name=$1
tier=$2
if [[ -n "${ns}" ]]; then
    namespace="namespace: {{ .Environment.Name }}-${name}"
else
    namespace="namespace: ${name}"
fi

helmfile "$1" "$2"
