{{- if .Values.controller.rbac.create }}
apiVersion: rbac.authorization.k8s.io/v1
{{- if .Values.rbac.singleNamespace }}
kind: RoleBinding
{{ else }}
kind: ClusterRoleBinding
{{- end }}
metadata:
  name: {{ include "argo-workflows.controller.fullname" . }}
  namespace: {{ .Release.Namespace | quote }}
  labels: {{- include "common.labels.standard" . | nindent 4 }}
    app.kubernetes.io/part-of: argo-workflows
    app.kubernetes.io/component: controller
    {{- if .Values.commonLabels }}
    {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }}
    {{- end }}
  {{- 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" . }}
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: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: {{ include "argo-workflows.controller.fullname" . }}-cluster-template
  namespace: {{ .Release.Namespace | quote }}
  labels: {{- include "common.labels.standard" . | nindent 4 }}
    app.kubernetes.io/component: controller
    {{- if .Values.commonLabels }}
    {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }}
    {{- end }}
  {{- 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" . }}-cluster-template
subjects:
  - kind: ServiceAccount
    name: {{ include "argo-workflows.controller.serviceAccountName" . }}
    namespace: {{ .Release.Namespace }}
{{- end }}
{{- end }}
