{{- $operatorNSIsManaged := has .Release.Namespace .Values.managedNamespaces -}}
{{- $fullName := include "eck-operator.fullname" . -}}
{{- $svcAccount := include "eck-operator.serviceAccountName" . }}
{{- $enableSecureMetrics := .Values.config.metrics.secureMode.enabled -}}

{{- if not .Values.createClusterScopedResources }}
{{- range .Values.managedNamespaces }}
{{- $namespace := . }}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: "{{ $fullName }}"
  namespace: {{ $namespace }}
  labels:
    {{- include "eck-operator.labels" $ | nindent 4 }}
rules:
{{ template "eck-operator.rbacRules" $ | toYaml | indent 2 }}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: "{{ $fullName }}"
  namespace: {{ $namespace }}
  labels:
    {{- include "eck-operator.labels" $ | nindent 4 }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: "{{ $fullName }}"
subjects:
- kind: ServiceAccount
  name: {{ $svcAccount }}
  namespace: {{ $.Release.Namespace }}
{{- end }} {{- /* end of range over managed namespaces */}}
{{- /* If createClusterScopedResources is false and operator namespace is not in the managed namespaces list, create additional role binding */}}
{{- if not $operatorNSIsManaged }}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: {{ $fullName }}
  namespace: {{ $.Release.Namespace }}
  labels:
    {{- include "eck-operator.labels" $ | nindent 4 }}
rules:
{{ template "eck-operator.rbacRules" $ | toYaml | indent 2 }}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: "{{ $fullName }}"
  namespace: {{ $.Release.Namespace }}
  labels:
    {{- include "eck-operator.labels" $ | nindent 4 }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: "{{ $fullName }}"
subjects:
- kind: ServiceAccount
  name: {{ $svcAccount }}
  namespace: {{ $.Release.Namespace }}
{{- end }} {{- /* end of operator role binding if operator namespace is not managed */}}
{{- else }} {{- /* we can create cluster-scoped resources so just create a cluster role binding */}}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding 
metadata:
  name: {{ $fullName }}
  labels:
    {{- include "eck-operator.labels" $ | nindent 4 }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: {{ $fullName }}
subjects:
- kind: ServiceAccount
  name: {{ $svcAccount }}
  namespace: {{ $.Release.Namespace }}
{{- if $enableSecureMetrics }}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  labels:
    {{- include "eck-operator.labels" $ | nindent 4 }}
  name: "{{ include "eck-operator.fullname" . }}-metrics-auth-rolebinding"
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: "{{ include "eck-operator.fullname" . }}-metrics-auth-role"
subjects:
- kind: ServiceAccount
  name: {{ $svcAccount }}
  namespace: {{ $.Release.Namespace }}
{{- end }}
{{- end }}
