#!/usr/bin/env bash

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/$name.yaml.gotmpl
  - ../values/$name/values/$name-{{ .Environment.Name }}.yaml.gotmpl
  postRenderer: ../bin/kustomizer
  postRendererArgs:
  - ../values/$name/kustomize/{{ .Environment.Name }}
  missingFileHandler: Info
- name: $name-manifests
  namespace: {{ .Environment.Name }}-$name
  chart: _$name-manifests
  condition: $name.enabled
  missingFileHandler: Info
  values:
  - ../values/values-{{ requiredEnv "CLUSTER_NAME" }}.yaml
  - ../values/$name/values.yaml.gotmpl
  - ../values/$name/values-{{ requiredEnv "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
    - _$name-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
