{{- if .Values.upgrade.enabled }}
{{- $ctx := dict "helm" . }}
{{- $_ := set $ctx "extraLabels" (dict "app.kubernetes.io/component" "upgrade-crds") }}
{{- $labels := include "vm.labels" $ctx }}
{{- $_ := unset $ctx "extraLabels" }}
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: {{ template "crds.upgrade.name" . }}
  namespace: {{ template "vm.namespace" . }}
  annotations:
    "helm.sh/hook": pre-install,pre-upgrade,pre-rollback
    "helm.sh/hook-weight": "-5"
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
  labels: {{ $labels | nindent 4 }}
  {{- $crds := .Files.Get "crds/crd.yaml" | splitList "---" }}
rules:
  - apiGroups:
      - "apiextensions.k8s.io"
    resources:
      - "customresourcedefinitions"
    verbs:
      - create
      - patch
      - update
      - get
      - list
    resourceNames:
      {{- range $crds }}
        {{- $crd := fromYaml . }}
      - {{ $crd.metadata.name }}
      {{- end }}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: {{ template "crds.upgrade.name" . }}
  namespace: {{ template "vm.namespace" . }}
  annotations:
    "helm.sh/hook": pre-install,pre-upgrade,pre-rollback
    "helm.sh/hook-weight": "-3"
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
  labels: {{ $labels | nindent 4 }}
subjects:
  - kind: ServiceAccount
    namespace: {{ template "vm.namespace" . }}
    name: {{ template "crds.upgrade.serviceAccountName" . }}
roleRef:
  kind: ClusterRole
  name: {{ template "crds.upgrade.name" . }}
  apiGroup: rbac.authorization.k8s.io
{{- end }}
