{{- /*
Copyright Broadcom, Inc. All Rights Reserved.
SPDX-License-Identifier: APACHE-2.0
*/}}

{{- if .Values.packaging.flux.enabled }}
{{- $versionLabel := dict "app.kubernetes.io/version" ( include "common.images.version" ( dict "imageRoot" .Values.kubeappsapis.image "chart" .Chart ) ) }}
{{- $labels := include "common.tplvalues.merge" ( dict "values" ( list .Values.commonLabels $versionLabel ) "context" . ) }}
{{- if .Values.rbac.create -}}
apiVersion: {{ include "common.capabilities.rbac.apiVersion" . }}
kind: ClusterRole
metadata:
  name: "kubeapps:controller:kubeapps-apis-fluxv2-plugin"
  labels: {{- include "common.labels.standard" ( dict "customLabels" $labels "context" $ ) | nindent 4 }}
    app.kubernetes.io/component: kubeappsapis
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
rules:
  - apiGroups: ["source.toolkit.fluxcd.io"]
    resources: ["helmrepositories"]
    verbs: ["get", "list", "watch"]
  # needed by fluxv2 plug-in to check whether flux CRDs have been installed
  - apiGroups: ["apiextensions.k8s.io"]
    resources: ["customresourcedefinitions"]
    verbs: ["get", "list"]
  # Temp hack to avoid
  # Failed to read secret for repo due to: rpc error: code = PermissionDenied desc = Forbidden
  # to get the secret 'helm-podinfo' due to 'secrets "helm-podinfo" is forbidden:
  # User "system:serviceaccount:kubeapps:kubeapps-internal-kubeappsapis" cannot get resource
  # "secrets" in API group "" in the namespace "default"'
  # see discussion in https://github.com/vmware-tanzu/kubeapps/pull/4932#issuecomment-1161243049
  - apiGroups:
    - ""
    resources:
    - secrets
    verbs:
    - get
---
apiVersion: {{ include "common.capabilities.rbac.apiVersion" . }}
kind: ClusterRoleBinding
metadata:
  name: "kubeapps:controller:kubeapps-apis-fluxv2-plugin"
  labels: {{- include "common.labels.standard" ( dict "customLabels" $labels "context" $ ) | nindent 4 }}
    app.kubernetes.io/component: kubeappsapis
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: "kubeapps:controller:kubeapps-apis-fluxv2-plugin"
subjects:
  - kind: ServiceAccount
    name: {{ template "kubeapps.kubeappsapis.serviceAccountName" . }}
    namespace: {{ include "common.names.namespace" . | quote }}
{{- end }}
{{- end }}
