{{- $cozyConfig := lookup "v1" "ConfigMap" "cozy-system" "cozystack" }}
{{- $bundleName := index $cozyConfig.data "bundle-name" }}
{{- $bundle := tpl (.Files.Get (printf "bundles/%s.yaml" $bundleName)) . | fromYaml }}
{{- $dependencyNamespaces := dict }}
{{- $disabledComponents := splitList "," ((index $cozyConfig.data "bundle-disable") | default "") }}

{{/* collect dependency namespaces from releases */}}
{{- range $x := $bundle.releases }}
{{- $_ := set $dependencyNamespaces $x.name $x.namespace }}
{{- end }}

{{- range $x := $bundle.releases }}
{{- if not (has $x.name $disabledComponents) }}
---
apiVersion: helm.toolkit.fluxcd.io/v2beta2
kind: HelmRelease
metadata:
  name: {{ $x.name }}
  namespace: {{ $x.namespace }}
  labels:
    cozystack.io/repository: system
spec:
  interval: 1m
  releaseName: {{ $x.releaseName | default $x.name }}
  install:
    crds: CreateReplace
    remediation:
      retries: -1
  upgrade:
    crds: CreateReplace
    remediation:
      retries: -1
  chart:
    spec:
      chart: {{ $x.chart }}
      reconcileStrategy: Revision
      sourceRef:
        kind: HelmRepository
        name: cozystack-system
        namespace: cozy-system
  {{- $values := dict }}
  {{- with $x.values }}
  {{- $values = merge . $values }}
  {{- end }}
  {{- with index $cozyConfig.data (printf "values-%s" $x.name) }}
  {{- $values = merge (fromYaml .) $values }}
  {{- end }}
  {{- with $values }}
  values:
    {{- toYaml . | nindent 4}}
  {{- end }}
  {{- with $x.dependsOn }}
  dependsOn:
  {{- range $dep := . }}
  {{- if not (has $dep $disabledComponents) }}
  - name: {{ $dep }}
    namespace: {{ index $dependencyNamespaces $dep }}
  {{- end }}
  {{- end }}
  {{- end }}
{{- end }}
{{- end }}
