{{/*
A role binding grants the permissions defined in a role to a user or set of users. It holds a list of subjects (users,
groups, or service accounts), and a reference to the role being granted. A RoleBinding grants permissions within a
specific namespace whereas a ClusterRoleBinding grants that access cluster-wide.

A RoleBinding may reference any Role in the same namespace. Alternatively, a RoleBinding can reference a ClusterRole and
bind that ClusterRole to the namespace of the RoleBinding. If you want to bind a ClusterRole to all the namespaces in
your cluster, you use a ClusterRoleBinding.

The name of a RoleBinding or ClusterRoleBinding object must be a valid path segment name.

Ref: https://kubernetes.io/docs/reference/access-authn-authz/rbac/
*/}}
{{- if .Values.include -}}
{{- if .Values.serviceAccount.create -}}
{{- if or .Values.serviceAccount.namespacePermissions .Values.serviceAccount.additionalNamespacePermissions }}
{{- $rules := list -}}
{{- $uniqueRules := concat $rules .Values.serviceAccount.namespacePermissions .Values.serviceAccount.additionalNamespacePermissions | uniq -}}
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: {{ include "app.serviceAccount.name" . }}
  namespace: {{ include "lib.namespace" . }}
  labels:
    app.kubernetes.io/component: {{ include "lib.componentName" . }}
    {{- include "lib.labels" . | nindent 4 }}
    {{- include "app.serviceAccount.additionalLabels" . | nindent 4 }}
  annotations:
    {{- include "lib.annotations" . | nindent 4 }}
    {{- include "app.serviceAccount.additionalAnnotations" . | nindent 4 }}
subjects:
  - kind: ServiceAccount
    name: {{ include "app.serviceAccount.name" . }}
    namespace: {{ include "lib.namespace" . }}
roleRef:
  kind: Role
  name: {{ include "app.serviceAccount.name" . }}
  apiGroup: rbac.authorization.k8s.io
{{- end -}}
{{- end -}}
{{- end -}}
