---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ include "hydra-maester.fullname" . }}-account
  namespace:  {{ .Release.Namespace }}
  labels:
    {{- include "hydra-maester.labels" . | nindent 4 }}
  {{- with .Values.deployment.serviceAccount.annotations }}
  annotations:
    {{- toYaml . | nindent 4 }}
  {{- end }}
{{- if not .Values.singleNamespaceMode }}
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: {{ include "hydra-maester.fullname" . }}-role
rules:
  - apiGroups: ["hydra.ory.sh"]
    resources: ["oauth2clients", "oauth2clients/status"]
    verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["list", "watch", "create"]
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: {{ include "hydra-maester.fullname" . }}-role-binding
subjects:
  - kind: ServiceAccount
    name: {{ include "hydra-maester.fullname" . }}-account # Service account assigned to the controller pod.
    namespace:  {{ .Release.Namespace }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: {{ include "hydra-maester.fullname" . }}-role
{{- end }}
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: {{ include "hydra-maester.fullname" . }}-role
  namespace:  {{ .Release.Namespace }}
rules:
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get", "list", "watch", "create"]
  - apiGroups: ["hydra.ory.sh"]
    resources: ["oauth2clients", "oauth2clients/status"]
    verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: {{ include "hydra-maester.fullname" . }}-role-binding
  namespace:  {{ .Release.Namespace }}
subjects:
  - kind: ServiceAccount
    name: {{ include "hydra-maester.fullname" . }}-account # Service account assigned to the controller pod.
    namespace:  {{ .Release.Namespace }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: {{ include "hydra-maester.fullname" . }}-role

{{- $name := include "hydra-maester.fullname" . -}}
{{- $namespace := .Release.Namespace -}}
{{- range .Values.enabledNamespaces }}
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: {{ $name }}-role
  namespace:  {{ . }}
rules:
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get", "list", "watch", "create", "update"]
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: {{ $name }}-role-binding
  namespace:  {{ . }}
subjects:
  - kind: ServiceAccount
    name: {{ $name }}-account # Service account assigned to the controller pod.
    namespace:  {{ $namespace }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: {{ $name }}-role
{{- end }}
