{{- if or .Values.serviceAccount.enabled -}}
{{- $fullName := include "oauth2-proxy.fullname" .  -}}
{{- $saName := include "oauth2-proxy.serviceAccountName" . -}}
{{- $name := include "oauth2-proxy.name" . -}}
{{- $namespace := include "oauth2-proxy.namespace" $ -}}
{{- $labels := include "oauth2-proxy.labels" . -}}
---
apiVersion: v1
kind: ServiceAccount
metadata:
  {{- with .Values.serviceAccount.annotations }}
  annotations:
    {{- toYaml . | nindent 4 }}
  {{- end }}
  labels:
    app: {{ $name }}
{{- $labels | indent 4 }}
  name: {{ $saName }}
  namespace: {{ $namespace }}
automountServiceAccountToken : {{ .Values.serviceAccount.automountServiceAccountToken }}
{{- if and .Values.redis.enabled .Values.initContainers.waitForRedis.enabled }}
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: {{ $fullName }}-watch-redis
  labels:
    app: {{ $name }}
    {{- $labels | nindent 4 }}
rules:
- apiGroups:
    - ""
  resources:
    - pods
  resourceNames:
    - "{{ include "oauth2-proxy.redis.fullname" . }}-master-0"
  verbs:
    - get
    - list
    - watch
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: {{ $saName }}-watch-redis
  labels:
    app: {{ $name }}
    {{- $labels | nindent 4 }}
subjects:
- kind: ServiceAccount
  name: {{ $saName }}
  apiGroup: ""
roleRef:
  kind: Role
  name: {{ $fullName }}-watch-redis
  apiGroup: ""
{{- end -}}
{{- end -}}
