{{- if .Values.rbac.create -}}
apiVersion: rbac.authorization.k8s.io/v1
kind: {{ .Values.namespaced | ternary "RoleBinding" "ClusterRoleBinding" }}
metadata:
  name: {{ printf "%s-viewer" (include "external-dns.fullname" .) }}
  labels:
    {{- include "external-dns.labels" . | nindent 4 }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: {{ .Values.namespaced | ternary "Role" "ClusterRole" }}
  name: {{ template "external-dns.fullname" . }}
subjects:
  - kind: ServiceAccount
    name: {{ template "external-dns.serviceAccountName" . }}
    namespace: {{ .Release.Namespace }}
{{- if and .Values.rbac.create .Values.namespaced (include "external-dns.hasGatewaySources" .) }}
{{- /*
     If namespaced=true and gatewayNamespace is NOT set, bind the namespaces ClusterRole.
     If gatewayNamespace IS set, we skip cluster-scoped RBAC entirely.
  */ -}}
{{- if not .Values.gatewayNamespace }}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: {{ template "external-dns.fullname" . }}-namespaces
  labels:
    {{- include "external-dns.labels" . | nindent 4 }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: {{ template "external-dns.fullname" . }}-namespaces
subjects:
  - kind: ServiceAccount
    name: {{ template "external-dns.serviceAccountName" . }}
    namespace: {{ .Release.Namespace }}
{{- end }}
{{- if .Values.gatewayNamespace }}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: {{ template "external-dns.fullname" . }}-gateway
  namespace: {{ .Values.gatewayNamespace }}
  labels:
    {{- include "external-dns.labels" . | nindent 4 }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: {{ template "external-dns.fullname" . }}-gateway
subjects:
  - kind: ServiceAccount
    name: {{ template "external-dns.serviceAccountName" . }}
    namespace: {{ .Release.Namespace }}
{{- end }}
{{- end }}
{{- end }}
