# _helpers.tpl
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "mercure.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 "mercure.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 "mercure.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Common labels
*/}}
{{- define "mercure.labels" -}}
app.kubernetes.io/name: {{ include "mercure.name" . }}
helm.sh/chart: {{ include "mercure.chart" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end -}}

{{/*
Create the name of the service account to use
*/}}
{{- define "mercure.serviceAccountName" -}}
{{- if .Values.serviceAccount.create -}}
    {{ default (include "mercure.fullname" .) .Values.serviceAccount.name }}
{{- else -}}
    {{ default "default" .Values.serviceAccount.name }}
{{- end -}}
{{- end -}}
 # backend-config.yaml
{{- if .Values.backendConfig.enabled -}}
apiVersion: cloud.google.com/v1beta1
kind: BackendConfig
metadata:
  name: {{ include "mercure.fullname" . }}
  labels:
{{ include "mercure.labels" . | indent 4 }}
spec:
  timeoutSec: {{ .Values.backendConfig.timeoutSec }}
{{- end }}
 # configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "mercure.fullname" . }}
  labels:
{{ include "mercure.labels" . | indent 4 }}
  annotations:
    "helm.sh/hook": "pre-install,pre-upgrade"
    "helm.sh/hook-delete-policy": "before-hook-creation"
data:
  allowAnonymous: {{ if .Values.allowAnonymous }}"1"{{ else }}"0"{{ end }}
  subscriptions: {{ if .Values.subscriptions }}"1"{{ else }}"0"{{ end }}
  metrics: {{ if .Values.metrics }}"1"{{ else }}"0"{{ end }}
  metricsLogin: {{ .Values.metricsLogin | quote }}
  corsAllowedOrigins: {{ join " " .Values.corsAllowedOrigins | quote }}
  debug: {{ if .Values.debug }}"1"{{ else }}"0"{{ end }}
  demo: {{ if .Values.demo }}"1"{{ else }}"0"{{ end }}
  logFormat: {{ .Values.logFormat | upper | quote }}
  publishAllowedOrigins: {{ join " " .Values.publishAllowedOrigins | quote }}
  heartbeatInterval: {{ .Values.heartbeatInterval | quote }}
  readTimeout: {{ .Values.readTimeout | quote }}
  writeTimeout: {{ .Values.writeTimeout | quote }}
  dispatchTimeout: {{ .Values.dispatchTimeout | quote }}
  compress: {{ if .Values.compress }}"1"{{ else }}"0"{{ end }}
  useForwardedHeaders: {{ if .Values.useForwardedHeaders }}"1"{{ else }}"0"{{ end }}
  jwtAlgorithm: {{ .Values.jwtAlgorithm | quote }}
 # deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "mercure.fullname" . }}
  labels:
{{ include "mercure.labels" . | indent 4 }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "mercure.name" . }}
      app.kubernetes.io/instance: {{ .Release.Name }}
  template:
    metadata:
      labels:
        app.kubernetes.io/name: {{ include "mercure.name" . }}
        app.kubernetes.io/instance: {{ .Release.Name }}
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
        checksum/secret: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }}
    spec:
    {{- with .Values.imagePullSecrets }}
      imagePullSecrets:
        {{- toYaml . | nindent 8 }}
    {{- end }}
      serviceAccountName: {{ template "mercure.serviceAccountName" . }}
      securityContext:
        {{- toYaml .Values.podSecurityContext | nindent 8 }}
      containers:
        - name: {{ .Chart.Name }}
          securityContext:
            {{- toYaml .Values.securityContext | nindent 12 }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            - name: http
              containerPort: 80
              protocol: TCP
          livenessProbe:
            httpGet:
              path: /healthz
              port: http
          readinessProbe:
            httpGet:
              path: /healthz
              port: http
          resources:
            {{- toYaml .Values.resources | nindent 12 }}
          env:
            - name: TRANSPORT_URL
              valueFrom:
                secretKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: transportUrl
            - name: ALLOW_ANONYMOUS
              valueFrom:
                configMapKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: allowAnonymous
            - name: SUBSCRIPTIONS
              valueFrom:
                configMapKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: subscriptions
            - name: METRICS
              valueFrom:
                configMapKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: metrics
            - name: METRICS_LOGIN
              valueFrom:
                configMapKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: metricsLogin
            - name: METRICS_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: metricsPassword
            - name: CORS_ALLOWED_ORIGINS
              valueFrom:
                configMapKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: corsAllowedOrigins
            - name: DEBUG
              valueFrom:
                configMapKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: debug
            - name: DEMO
              valueFrom:
                configMapKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: demo
            - name: JWT_ALGORITHM
              valueFrom:
                configMapKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: jwtAlgorithm
            - name: JWT_KEY
              valueFrom:
                secretKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: jwtKey
            - name: LOG_FORMAT
              valueFrom:
                configMapKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: logFormat
            - name: PUBLISH_ALLOWED_ORIGINS
              valueFrom:
                configMapKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: publishAllowedOrigins
            - name: PUBLISHER_JWT_KEY
              valueFrom:
                secretKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: publisherJwtKey
            - name: SUBSCRIBER_JWT_KEY
              valueFrom:
                secretKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: subscriberJwtKey
            - name: HEARTBEAT_INTERVAL
              valueFrom:
                configMapKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: heartbeatInterval
            - name: READ_TIMEOUT
              valueFrom:
                configMapKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: readTimeout
            - name: WRITE_TIMEOUT
              valueFrom:
                configMapKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: writeTimeout
            - name: DISPATCH_TIMEOUT
              valueFrom:
                configMapKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: dispatchTimeout
            - name: COMPRESS
              valueFrom:
                configMapKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: compress
            - name: USE_FORWARDED_HEADERS
              valueFrom:
                configMapKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: useForwardedHeaders
            - name: SUBSCRIBER_JWT_KEY
              valueFrom:
                secretKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: subscriberJwtKey
            - name: LICENSE
              valueFrom:
                secretKeyRef:
                  name: {{ include "mercure.fullname" . }}
                  key: license
      {{- with .Values.nodeSelector }}
      nodeSelector:
        {{- toYaml . | nindent 8 }}
      {{- end }}
    {{- with .Values.affinity }}
      affinity:
        {{- toYaml . | nindent 8 }}
    {{- end }}
    {{- with .Values.tolerations }}
      tolerations:
        {{- toYaml . | nindent 8 }}
    {{- end }}
 # ingress.yaml
{{- if .Values.ingress.enabled -}}
{{- $fullName := include "mercure.fullname" . -}}
{{- $svcPort := .Values.service.port -}}
{{- if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}}
apiVersion: networking.k8s.io/v1beta1
{{- else -}}
apiVersion: extensions/v1beta1
{{- end }}
kind: Ingress
metadata:
  name: {{ $fullName }}
  labels:
{{ include "mercure.labels" . | indent 4 }}
  {{- with .Values.ingress.annotations }}
  annotations:
    {{- toYaml . | nindent 4 }}
  {{- end }}
spec:
{{- if .Values.ingress.tls }}
  tls:
  {{- range .Values.ingress.tls }}
    - hosts:
      {{- range .hosts }}
        - {{ . | quote }}
      {{- end }}
      secretName: {{ .secretName }}
  {{- end }}
{{- end }}
  rules:
  {{- range .Values.ingress.hosts }}
    - host: {{ .host | quote }}
      http:
        paths:
        {{- range .paths }}
          - path: {{ . }}
            backend:
              serviceName: {{ $fullName }}
              servicePort: {{ $svcPort }}
        {{- end }}
  {{- end }}
{{- end }}
 # secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: {{ include "mercure.fullname" . }}
  annotations:
    "helm.sh/hook": "pre-install,pre-upgrade"
    "helm.sh/hook-delete-policy": "before-hook-creation"
  labels:
{{ include "mercure.labels" . | indent 4 }}
type: Opaque
data:
  transportUrl: {{ .Values.transportUrl | b64enc | quote }}
  jwtKey: {{ .Values.jwtKey | default (randAlphaNum 12) | b64enc | quote }}
  publisherJwtKey: {{ .Values.publisherJwtKey | b64enc | quote }}
  subscriberJwtKey: {{ .Values.subscriberJwtKey | b64enc | quote }}
  metricsPassword: {{ .Values.metricsPassword | default (randAlphaNum 12) | b64enc | quote }}
  license: {{ .Values.license | b64enc | quote }}
 # service.yaml
apiVersion: v1
kind: Service
metadata:
  name: {{ include "mercure.fullname" . }}
  labels:
{{ include "mercure.labels" . | indent 4 }}
  {{- if .Values.backendConfig.enabled }}
  annotations:
    beta.cloud.google.com/backend-config: '{"default": "{{ include "mercure.fullname" . }}"}'
  {{- end }}
spec:
  type: {{ .Values.service.type }}
  ports:
    - port: {{ .Values.service.port }}
      targetPort: http
      protocol: TCP
      name: http
  selector:
    app.kubernetes.io/name: {{ include "mercure.name" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
 # serviceaccount.yaml
{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ template "mercure.serviceAccountName" . }}
  labels:
{{ include "mercure.labels" . | indent 4 }}
{{- end -}}
 # test-connection.yaml
apiVersion: v1
kind: Pod
metadata:
  name: "{{ include "mercure.fullname" . }}-test-connection"
  labels:
{{ include "mercure.labels" . | indent 4 }}
  annotations:
    "helm.sh/hook": test-success
spec:
  containers:
    - name: wget
      image: busybox
      command: ['wget']
      args:  ['{{ include "mercure.fullname" . }}:{{ .Values.service.port }}']
  restartPolicy: Never

# Default values for mercure.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.

transportUrl: bolt://updates.db?size=0&cleanup_frequency=0.3
allowAnonymous: false
subscriptions: false
metrics: false
metricsLogin: "mercure"
metricsPassword: ""
corsAllowedOrigins: []
debug: false
demo: false
jwtAlgorithm: HS256
jwtKey: ""
logFormat: FLUENTD
publishAllowedOrigins: []
publisherJwtKey: ""
subscriberJwtKey: ""
heartbeatInterval: "0s"
readTimeout: "5s"
writeTimeout: "60s"
dispatchTimeout: "5s"
compress: false
useForwardedHeaders: false
license: ""

# GCP load balancers by default terminate connections after 30 seconds. This can be changed by
# enabling the following backendConfig and changing the `timeoutSec` property.
# More info at: https://github.com/dunglas/mercure/issues/106 and
# https://cloud.google.com/kubernetes-engine/docs/how-to/configure-backend-service
backendConfig:
  enabled: false
  timeoutSec: 30

# replicaCount MUST be 1 if you use the BoltDB transport (the default)
replicaCount: 1

image:
  repository: dunglas/mercure
  tag: v0.10
  pullPolicy: IfNotPresent

imagePullSecrets: []
nameOverride: ""
fullnameOverride: ""

serviceAccount:
  # Specifies whether a service account should be created
  create: true
  # The name of the service account to use.
  # If not set and create is true, a name is generated using the fullname template
  name:

podSecurityContext: {}
  # fsGroup: 2000

securityContext: {}
  # capabilities:
  #   drop:
  #   - ALL
  # readOnlyRootFilesystem: true
  # runAsNonRoot: true
  # runAsUser: 1000

service:
  type: ClusterIP
  port: 80

ingress:
  enabled: false
  annotations: {}
    # kubernetes.io/ingress.class: nginx
    # kubernetes.io/tls-acme: "true"
  hosts:
    - host: mercure.local
      paths: []

  tls: []
  #  - secretName: chart-example-tls
  #    hosts:
  #      - chart-example.local

resources: {}
  # We usually recommend not to specify default resources and to leave this as a conscious
  # choice for the user. This also increases chances charts run on environments with little
  # resources, such as Minikube. If you do want to specify resources, uncomment the following
  # lines, adjust them as necessary, and remove the curly braces after 'resources:'.
  # limits:
  #   cpu: 100m
  #   memory: 128Mi
  # requests:
  #   cpu: 100m
  #   memory: 128Mi

nodeSelector: {}

tolerations: []

affinity: {}
