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

{{/* collect namespaces from releases */}}
{{- range $x := $bundle.releases }}
  {{- if not (hasKey $namespaces $x.namespace) }}
    {{- if not (has $x.name $disabledComponents) }}
      {{- if or (not $x.optional) (and ($x.optional) (has $x.name $enabledComponents)) }}
        {{- $_ := set $namespaces $x.namespace false }}
      {{- end }}
    {{- end }}
  {{- end }}
  {{/* if at least one release requires a privileged namespace, then it should be privileged */}}
  {{- if or $x.privileged (index $namespaces $x.namespace) }}
    {{- $_ := set $namespaces $x.namespace true }}
  {{- end }}
{{- end }}

{{/* Add extra namespaces */}}
{{- $_ := set $namespaces "cozy-system" true }}
{{- $_ := set $namespaces "cozy-public" false }}

{{- range $namespace, $privileged := $namespaces }}
---
apiVersion: v1
kind: Namespace
metadata:
  annotations:
    "helm.sh/resource-policy": keep
  labels:
    cozystack.io/system: "true"
    {{- if $privileged }}
    pod-security.kubernetes.io/enforce: privileged
    {{- end }}
  name: {{ $namespace }}
{{- end }}
