# _helpers.tpl
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "oauth2-proxy.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "oauth2-proxy.fullname" -}}
{{- if .Values.fullnameOverride -}}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default .Chart.Name .Values.nameOverride -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end -}}

{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "oauth2-proxy.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Get the secret name.
*/}}
{{- define "oauth2-proxy.secretName" -}}
{{- if .Values.config.existingSecret -}}
{{- printf "%s" .Values.config.existingSecret -}}
{{- else -}}
{{- printf "%s" (include "oauth2-proxy.fullname" .) -}}
{{- end -}}
{{- end -}}

{{/*
Create the name of the service account to use
*/}}
{{- define "oauth2-proxy.serviceAccountName" -}}
{{- if .Values.serviceAccount.enabled -}}
    {{ default (include "oauth2-proxy.fullname" .) .Values.serviceAccount.name }}
{{- else -}}
    {{ default "default" .Values.serviceAccount.name }}
{{- end -}}
{{- end -}}
 # configmap-authenticated-emails-file.yaml
{{- if .Values.authenticatedEmailsFile.enabled }}
{{- if .Values.authenticatedEmailsFile.restricted_access }}
apiVersion: v1
kind: ConfigMap
metadata:
  labels:
    app: {{ template "oauth2-proxy.name" . }}
    chart: {{ template "oauth2-proxy.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
  name: {{ template "oauth2-proxy.fullname" . }}-accesslist
data:
  restricted_user_access: {{ .Values.authenticatedEmailsFile.restricted_access | quote }}
{{- end }}
{{- end }}
 # configmap-htpasswd-file.yaml
{{- if and .Values.htpasswdFile.enabled (not .Values.htpasswdFile.existingSecret) }}
apiVersion: v1
kind: Secret
metadata:
  labels:
    app: {{ template "oauth2-proxy.name" . }}
    chart: {{ template "oauth2-proxy.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
  name: {{ template "oauth2-proxy.fullname" . }}-htpasswd-file
type: Opaque
stringData:
  users.txt: |-
    {{- range $entries := .Values.htpasswdFile.entries }}
    {{ $entries }}
    {{- end -}}
{{- end }} # configmap.yaml
{{- if not .Values.config.existingConfig }}
{{- if .Values.config.configFile }}
apiVersion: v1
kind: ConfigMap
metadata:
  labels:
    app: {{ template "oauth2-proxy.name" . }}
    chart: {{ template "oauth2-proxy.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
  name: {{ template "oauth2-proxy.fullname" . }}
data:
  oauth2_proxy.cfg: {{ .Values.config.configFile | quote }}
{{- end }}
{{- end }}
 # deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: {{ template "oauth2-proxy.name" . }}
    chart: {{ template "oauth2-proxy.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
  name: {{ template "oauth2-proxy.fullname" . }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app: {{ template "oauth2-proxy.name" . }}
      release: {{ .Release.Name }}
  template:
    metadata:
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
        checksum/config-emails: {{ include (print $.Template.BasePath "/configmap-authenticated-emails-file.yaml") . | sha256sum }}
        checksum/secret: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }}
        checksum/google-secret: {{ include (print $.Template.BasePath "/google-secret.yaml") . | sha256sum }}
{{- if .Values.htpasswdFile.enabled }}
        checksum/htpasswd: {{ include (print $.Template.BasePath "/configmap-htpasswd-file.yaml") . | sha256sum }}
{{- end }}
    {{- if .Values.podAnnotations }}
{{ toYaml .Values.podAnnotations | indent 8 }}
    {{- end }}
      labels:
        app: {{ template "oauth2-proxy.name" . }}
        release: "{{ .Release.Name }}"
      {{- if .Values.podLabels }}
{{ toYaml .Values.podLabels | indent 8 }}
      {{- end }}
    spec:
    {{- if .Values.priorityClassName }}
      priorityClassName: "{{ .Values.priorityClassName }}"
    {{- end }}
      {{- with .Values.podSecurityContext }}
      securityContext:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      serviceAccountName: {{ template "oauth2-proxy.serviceAccountName" . }}
      containers:
      - name: {{ .Chart.Name }}
        image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
        imagePullPolicy: {{ .Values.image.pullPolicy }}
        args:
          - --http-address=0.0.0.0:4180
        {{- range $key, $value := .Values.extraArgs }}
          {{- if $value }}
          - --{{ $key }}={{ $value }}
          {{- else }}
          - --{{ $key }}
          {{- end }}
        {{- end }}
        {{- if or .Values.config.existingConfig .Values.config.configFile }}
          - --config=/etc/oauth2_proxy/oauth2_proxy.cfg
        {{- end }}
        {{- if .Values.authenticatedEmailsFile.enabled }}
        {{- if .Values.authenticatedEmailsFile.template }}
          - --authenticated-emails-file=/etc/oauth2-proxy/{{ .Values.authenticatedEmailsFile.template }}
        {{- else }}
          - --authenticated-emails-file=/etc/oauth2-proxy/authenticated-emails-list
        {{- end }}
        {{- end }}
        {{- with .Values.config.google }}
        {{- if and .adminEmail (or .serviceAccountJson .existingSecret) }}
          - --google-admin-email={{ .adminEmail }}
          - --google-service-account-json=/google/service-account.json
        {{- end }}
        {{- end }}
        {{- if .Values.htpasswdFile.enabled }}
          - --htpasswd-file=/etc/oauth2_proxy/htpasswd/users.txt
        {{- end }}
        env:
        {{- if .Values.proxyVarsAsSecrets }}
        - name: OAUTH2_PROXY_CLIENT_ID
          valueFrom:
            secretKeyRef:
              name:  {{ template "oauth2-proxy.secretName" . }}
              key: client-id
        - name: OAUTH2_PROXY_CLIENT_SECRET
          valueFrom:
            secretKeyRef:
              name:  {{ template "oauth2-proxy.secretName" . }}
              key: client-secret
        - name: OAUTH2_PROXY_COOKIE_SECRET
          valueFrom:
            secretKeyRef:
              name:  {{ template "oauth2-proxy.secretName" . }}
              key: cookie-secret
        {{- end }}
        {{- if .Values.extraEnv }}
{{ toYaml .Values.extraEnv | indent 8 }}
        {{- end }}
        ports:
          - containerPort: 4180
            name: {{ .Values.httpScheme }}
            protocol: TCP
{{- if .Values.livenessProbe.enabled }}
        livenessProbe:
          httpGet:
            path: /ping
            port: {{ .Values.httpScheme }}
            scheme: {{ .Values.httpScheme | upper }}
          initialDelaySeconds: {{ .Values.livenessProbe.initialDelaySeconds }}
          timeoutSeconds: {{ .Values.livenessProbe.timeoutSeconds }}
{{- end }}
{{- if .Values.readinessProbe.enabled }}
        readinessProbe:
          httpGet:
            path: /ping
            port: {{ .Values.httpScheme }}
            scheme: {{ .Values.httpScheme | upper }}
          initialDelaySeconds: {{ .Values.readinessProbe.initialDelaySeconds }}
          timeoutSeconds: {{ .Values.readinessProbe.timeoutSeconds }}
          successThreshold: {{ .Values.readinessProbe.successThreshold }}
          periodSeconds: {{ .Values.readinessProbe.periodSeconds }}
{{- end }}
        resources:
{{ toYaml .Values.resources | indent 10 }}
        volumeMounts:
{{- with .Values.config.google }}
{{- if and .adminEmail (or .serviceAccountJson .existingSecret) }}
        - name: google-secret
          mountPath: /google
          readOnly: true
{{- end }}
{{- end }}
{{- if or .Values.config.existingConfig .Values.config.configFile }}
        - mountPath: /etc/oauth2_proxy
          name: configmain
{{- end }}
{{- if .Values.authenticatedEmailsFile.enabled }}
        - mountPath: /etc/oauth2-proxy
          name: configaccesslist
          readOnly: true
{{- end }}
{{- if .Values.htpasswdFile.enabled }}
        - mountPath: /etc/oauth2_proxy/htpasswd
          name: {{ template "oauth2-proxy.fullname" . }}-htpasswd-file
          readOnly: true
{{- end }}
{{- if ne (len .Values.extraVolumeMounts) 0 }}
{{ toYaml .Values.extraVolumeMounts | indent 8 }}
{{- end }}
{{- if .Values.securityContext.enabled }}
        securityContext:
          runAsNonRoot: {{ .Values.securityContext.runAsNonRoot }}
{{- end}}
      volumes:
{{- with .Values.config.google }}
{{- if and .adminEmail (or .serviceAccountJson .existingSecret) }}
      - name: google-secret
        secret:
          secretName: {{ if .existingSecret }}{{ .existingSecret }}{{ else }} {{ template "oauth2-proxy.secretName" $ }}{{ end }}
{{- end }}
{{- end }}

{{- if .Values.htpasswdFile.enabled }}
      - name: {{ template "oauth2-proxy.fullname" . }}-htpasswd-file
        secret:
          secretName: {{ if .Values.htpasswdFile.existingSecret }}{{ .Values.htpasswdFile.existingSecret }}{{ else }} {{ template "oauth2-proxy.fullname" . }}-htpasswd-file {{ end }}
{{- end }}

{{- if or .Values.config.existingConfig .Values.config.configFile }}
      - configMap:
          defaultMode: 420
          name: {{ if .Values.config.existingConfig }}{{ .Values.config.existingConfig }}{{ else }}{{ template "oauth2-proxy.fullname" . }}{{ end }}
        name: configmain
{{- end }}
{{- if ne (len .Values.extraVolumes) 0 }}
{{ toYaml .Values.extraVolumes | indent 6 }}
{{- end }}
{{- if .Values.authenticatedEmailsFile.enabled }}
      - configMap:
{{- if .Values.authenticatedEmailsFile.template }}
          name: {{ .Values.authenticatedEmailsFile.template }}
{{- else }}
          name: {{ template "oauth2-proxy.fullname" . }}-accesslist
{{- end }}
          items:
          - key: restricted_user_access
{{- if .Values.authenticatedEmailsFile.template }}
            path: {{ .Values.authenticatedEmailsFile.template }}
{{- else }}
            path: authenticated-emails-list
{{- end }}
        name: configaccesslist
{{- end }}

      {{- if .Values.imagePullSecrets }}
      imagePullSecrets:
{{ toYaml .Values.imagePullSecrets | indent 8 }}
      {{- end }}
    {{- if .Values.affinity }}
      affinity:
{{ toYaml .Values.affinity | indent 8 }}
    {{- end }}
    {{- if .Values.nodeSelector }}
      nodeSelector:
{{ toYaml .Values.nodeSelector | indent 8 }}
    {{- end }}
      tolerations:
{{ toYaml .Values.tolerations | indent 8 }}
 # google-secret.yaml
{{- if and .Values.config.google (not .Values.config.google.existingSecret) }}
apiVersion: v1
kind: Secret
metadata:
  labels:
    app: {{ template "oauth2-proxy.name" . }}
    chart: {{ template "oauth2-proxy.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
  name: {{ template "oauth2-proxy.fullname" . }}-google
type: Opaque
data:
  service-account.json: {{ .serviceAccountJson }}
{{- end -}}
 # ingress.yaml
{{- if .Values.ingress.enabled -}}
{{- $serviceName := include "oauth2-proxy.fullname" . -}}
{{- $servicePort := .Values.service.port -}}
{{- $ingressPath := .Values.ingress.path -}}
{{- $extraPaths := .Values.ingress.extraPaths -}}
{{- if .Capabilities.APIVersions.Has "networking.k8s.io/v1beta1" -}}
apiVersion: networking.k8s.io/v1beta1
{{- else -}}
apiVersion: extensions/v1beta1
{{- end }}
kind: Ingress
metadata:
  labels:
    app: {{ template "oauth2-proxy.name" . }}
    chart: {{ template "oauth2-proxy.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
  name: {{ template "oauth2-proxy.fullname" . }}
{{- with .Values.ingress.annotations }}
  annotations:
{{ toYaml . | indent 4 }}
{{- end }}
spec:
  rules:
    {{- range $host := .Values.ingress.hosts }}
    - host: {{ $host | quote }}
      http:
        paths:
{{ if $extraPaths }}
{{ toYaml $extraPaths | indent 10 }}
{{- end }}
          - path: {{ $ingressPath }}
            backend:
              serviceName: {{ $serviceName }}
              servicePort: {{ $servicePort }}
    {{- end -}}
  {{- if .Values.ingress.tls }}
  tls:
{{ toYaml .Values.ingress.tls | indent 4 }}
  {{- end -}}
{{- end -}}
 # poddisruptionbudget.yaml
{{- if and .Values.podDisruptionBudget.enabled (gt (.Values.replicaCount | int) 1) }}
apiVersion: policy/v1beta1
kind: PodDisruptionBudget
metadata:
  labels:
    app: {{ template "oauth2-proxy.name" . }}
    chart: {{ template "oauth2-proxy.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
  name: {{ template "oauth2-proxy.fullname" . }}
spec:
  selector:
    matchLabels:
      app: {{ template "oauth2-proxy.name" . }}
      release: {{ .Release.Name }}
  minAvailable: {{ .Values.podDisruptionBudget.minAvailable }}
{{- end }}
 # secret.yaml
{{- if and (not .Values.config.existingSecret) (.Values.proxyVarsAsSecrets) }}
apiVersion: v1
kind: Secret
metadata:
  labels:
    app: {{ template "oauth2-proxy.name" . }}
    chart: {{ template "oauth2-proxy.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
  name: {{ template "oauth2-proxy.fullname" . }}
type: Opaque
data:
  cookie-secret: {{ .Values.config.cookieSecret | b64enc | quote }}
  client-secret: {{ .Values.config.clientSecret | b64enc | quote }}
  client-id: {{ .Values.config.clientID | b64enc | quote }}
{{- end -}}
 # service.yaml
apiVersion: v1
kind: Service
metadata:
  labels:
    app: {{ template "oauth2-proxy.name" . }}
    chart: {{ template "oauth2-proxy.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
  name: {{ template "oauth2-proxy.fullname" . }}
{{- if .Values.service.annotations }}
  annotations:
{{ toYaml .Values.service.annotations | indent 4 }}
{{- end }}
spec:
{{- if (or (eq .Values.service.type "ClusterIP") (empty .Values.service.type)) }}
  type: ClusterIP
  {{- if .Values.service.clusterIP }}
  clusterIP: {{ .Values.service.clusterIP }}
  {{end}}
{{- else if eq .Values.service.type "LoadBalancer" }}
  type: {{ .Values.service.type }}
  {{- if .Values.service.loadBalancerIP }}
  loadBalancerIP: {{ .Values.service.loadBalancerIP }}
  {{- end }}
  {{- if .Values.service.loadBalancerSourceRanges }}
  loadBalancerSourceRanges:
{{ toYaml .Values.service.loadBalancerSourceRanges | indent 4 }}
  {{- end -}}
{{- else }}
  type: {{ .Values.service.type }}
{{- end }}
  ports:
    - port: {{ .Values.service.port }}
      targetPort: {{ .Values.httpScheme }}
      protocol: TCP
      name: {{ .Values.httpScheme }}
  selector:
    app: {{ template "oauth2-proxy.name" . }}
    release: {{ .Release.Name }}
 # serviceaccount.yaml
{{- if or .Values.serviceAccount.enabled -}}
apiVersion: v1
kind: ServiceAccount
metadata:
  {{- with .Values.serviceAccount.annotations }}
  annotations:
    {{- toYaml . | nindent 4 }}
  {{- end }}
  labels:
    app: {{ template "oauth2-proxy.name" . }}
    chart: {{ template "oauth2-proxy.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
  name: {{ template "oauth2-proxy.fullname" . }}
{{- end -}}

# Oauth client configuration specifics
config:
  # OAuth client ID
  clientID: "XXXXXXX"
  # OAuth client secret
  clientSecret: "XXXXXXXX"
  # Create a new secret with the following command
  # openssl rand -base64 32 | head -c 32 | base64
  # Use an existing secret for OAuth2 credentials (see secret.yaml for required fields)
  # Example:
  # existingSecret: secret
  cookieSecret: "XXXXXXXXXX"
  google: {}
    # adminEmail: xxxx
    # serviceAccountJson: xxxx
    # Alternatively, use an existing secret (see google-secret.yaml for required fields)
    # Example:
    # existingSecret: google-secret
  # Default configuration, to be overridden
  configFile: |-
    email_domains = [ "*" ]
    upstreams = [ "file:///dev/null" ]
  # Custom configuration file: oauth2_proxy.cfg
  # configFile: |-
  #   pass_basic_auth = false
  #   pass_access_token = true
  # Use an existing config map (see configmap.yaml for required fields)
  # Example:
  # existingConfig: config

image:
  repository: "quay.io/pusher/oauth2_proxy"
  tag: "v5.1.0"
  pullPolicy: "IfNotPresent"

# Optionally specify an array of imagePullSecrets.
# Secrets must be manually created in the namespace.
# ref: https://kubernetes.io/docs/concepts/containers/images/#specifying-imagepullsecrets-on-a-pod
# imagePullSecrets:
  # - name: myRegistryKeySecretName

extraArgs: {}
extraEnv: []

# To authorize individual email addresses
# That is part of extraArgs but since this needs special treatment we need to do a separate section
authenticatedEmailsFile:
  enabled: false
  # template is the name of the configmap what contains the email user list but has been configured without this chart.
  # It's a simpler way to maintain only one configmap (user list) instead changing it for each oauth2-proxy service.
  # Be aware the value name in the extern config map in data needs to be named to "restricted_user_access".
  template: ""
  # One email per line
  # example:
  # restricted_access: |-
  #   name1@domain
  #   name2@domain
  # If you override the config with restricted_access it will configure a user list within this chart what takes care of the
  # config map resource.
  restricted_access: ""

service:
  type: ClusterIP
  # when service.type is ClusterIP ...
  # clusterIP: 192.0.2.20
  # when service.type is LoadBalancer ...
  # loadBalancerIP: 198.51.100.40
  # loadBalancerSourceRanges: 203.0.113.0/24
  port: 80
  annotations: {}
  # foo.io/bar: "true"

## Create or use ServiceAccount
serviceAccount:
  ## Specifies whether a ServiceAccount should be created
  enabled: true
  ## The name of the ServiceAccount to use.
  ## If not set and create is true, a name is generated using the fullname template
  name:
  annotations: {}

ingress:
  enabled: false
  path: /
  # Used to create an Ingress record.
  # hosts:
    # - chart-example.local
  # Extra paths to prepend to every host configuration. This is useful when working with annotation based services.
  # extraPaths:
  # - path: /*
  #   backend:
  #     serviceName: ssl-redirect
  #     servicePort: use-annotation
  # annotations:
  #   kubernetes.io/ingress.class: nginx
  #   kubernetes.io/tls-acme: "true"
  # tls:
    # Secrets must be manually created in the namespace.
    # - secretName: chart-example-tls
    #   hosts:
    #     - chart-example.local

resources: {}
  # limits:
  #   cpu: 100m
  #   memory: 300Mi
  # requests:
  #   cpu: 100m
  #   memory: 300Mi

extraVolumes: []
  # - name: ca-bundle-cert
  #   secret:
  #     secretName: <secret-name>

extraVolumeMounts: []
  # - mountPath: /etc/ssl/certs/
  #   name: ca-bundle-cert

priorityClassName: ""

# Affinity for pod assignment
# Ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#affinity-and-anti-affinity
# affinity: {}

# Tolerations for pod assignment
# Ref: https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/
tolerations: []

# Node labels for pod assignment
# Ref: https://kubernetes.io/docs/user-guide/node-selection/
nodeSelector: {}

# Whether to use secrets instead of environment values for setting up OAUTH2_PROXY variables
proxyVarsAsSecrets: true

# Configure Kubernetes liveness and readiness probes.
# Ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/
# Disable both when deploying with Istio 1.0 mTLS. https://istio.io/help/faq/security/#k8s-health-checks
livenessProbe:
  enabled: true
  initialDelaySeconds: 0
  timeoutSeconds: 1

readinessProbe:
  enabled: true
  initialDelaySeconds: 0
  timeoutSeconds: 1
  periodSeconds: 10
  successThreshold: 1

# Configure Kubernetes security context for container
# Ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
securityContext:
  enabled: false
  runAsNonRoot: true

podAnnotations: {}
podLabels: {}
replicaCount: 1

## PodDisruptionBudget settings
## ref: https://kubernetes.io/docs/concepts/workloads/pods/disruptions/
podDisruptionBudget:
  enabled: true
  minAvailable: 1

# Configure Kubernetes security context for pod
# Ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
podSecurityContext: {}

# whether to use http or https
httpScheme: http

# Additionally authenticate against a htpasswd file. Entries must be created with "htpasswd -s" for SHA encryption.
# Alternatively supply an existing secret which contains the required information.
htpasswdFile:
  enabled: false
  existingSecret: ""
  entries: {}
  # One row for each user
  # example:
  # entries:
  #  - testuser:{SHA}EWhzdhgoYJWy0z2gyzhRYlN9DSiv
