{{- $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 "") }}
{{- $enabledComponents := splitList "," ((index $cozyConfig.data "bundle-enable") | default "") }}

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

{{- range $x := $bundle.releases }}

{{- $shouldInstall := true }}
{{- $shouldDelete := false }}
{{- if or (has $x.name $disabledComponents) (and ($x.optional) (not (has $x.name $enabledComponents))) }}
{{-   $shouldInstall = false }}
{{-   if $.Capabilities.APIVersions.Has "helm.toolkit.fluxcd.io/v2" }}
{{-     if lookup "helm.toolkit.fluxcd.io/v2" "HelmRelease" $x.namespace $x.name }}
{{-       $shouldDelete = true }}
{{-     end }}
{{-   end }}
{{- end }}

{{- if or $shouldInstall $shouldDelete }}
---
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
  name: {{ $x.name }}
  namespace: {{ $x.namespace }}
  labels:
    cozystack.io/repository: system
    cozystack.io/system-app: "true"
    {{- if $shouldDelete }}
    cozystack.io/marked-for-deletion: "true"
    {{- end }}
spec:
  interval: 5m
  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
      version: '>= 0.0.0-0'
      {{- with $x.valuesFiles }}
      valuesFiles:
      {{- toYaml $x.valuesFiles | nindent 6 }}
      {{- end }}
  {{- $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 }}
