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

{{- if .Values.controller.rbac.create }}
{{- $versionLabel := dict "app.kubernetes.io/version" ( include "common.images.version" ( dict "imageRoot" .Values.controller.image "chart" .Chart ) ) }}
{{- $labels := include "common.tplvalues.merge" ( dict "values" ( list .Values.commonLabels $versionLabel ) "context" . ) }}
apiVersion: {{ include "common.capabilities.rbac.apiVersion" . }}
{{- if .Values.rbac.singleNamespace }}
kind: RoleBinding
{{ else }}
kind: ClusterRoleBinding
{{- end }}
metadata:
  name: {{ include "argo-workflows.controller.fullname.namespace" . }}
  {{- if .Values.rbac.singleNamespace }}
  namespace: {{ .Release.Namespace | quote }}
  {{- end }}
  labels: {{- include "common.labels.standard" ( dict "customLabels" $labels "context" $ ) | nindent 4 }}
    app.kubernetes.io/part-of: argo-workflows
    app.kubernetes.io/component: controller
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  {{- if .Values.rbac.singleNamespace }}
  kind: Role
  {{ else }}
  kind: ClusterRole
  {{- end }}
  name: {{ include "argo-workflows.controller.fullname.namespace" . }}
subjects:
  - kind: ServiceAccount
    name: {{ include "argo-workflows.controller.serviceAccountName" . }}
    namespace: {{ .Release.Namespace }}
{{- if .Values.controller.workflowNamespaces }}
{{- $uiServiceAccount := (include "argo-workflows.controller.serviceAccountName" .) }}
{{- $namespace := .Release.Namespace }}
{{- range $key := .Values.controller.workflowNamespaces }}
  {{- if not (eq $key $namespace) }}
  - kind: ServiceAccount
    name: {{ $uiServiceAccount }}
    namespace: {{ $key }}
  {{- end }}
{{- end }}
{{- end }}

{{- if .Values.controller.clusterWorkflowTemplates.enabled }}
---
apiVersion: {{ include "common.capabilities.rbac.apiVersion" . }}
kind: ClusterRoleBinding
metadata:
  name: {{ include "argo-workflows.controller.fullname.namespace" . }}-cluster-template
  labels: {{- include "common.labels.standard" ( dict "customLabels" $labels "context" $ ) | nindent 4 }}
    app.kubernetes.io/component: controller
  {{- 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: {{ include "argo-workflows.controller.fullname.namespace" . }}-cluster-template
subjects:
  - kind: ServiceAccount
    name: {{ include "argo-workflows.controller.serviceAccountName" . }}
    namespace: {{ .Release.Namespace }}
{{- end }}
{{- end }}
