# _helpers.tpl
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "rocketchat.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).
*/}}
{{- define "rocketchat.fullname" -}}
{{- $name := default .Chart.Name .Values.nameOverride -}}
{{- printf "%s-%s" .Release.Name $name | 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).
*/}}
{{- define "rocketchat.mongodb.fullname" -}}
{{- printf "%s-%s" .Release.Name "mongodb" | trunc 63 | trimSuffix "-" -}}
{{- end -}}

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

{{/*
Create the name of the service account to use
*/}}
{{- define "rocketchat.serviceAccountName" -}}
{{- if .Values.serviceAccount.create -}}
    {{ default (include "rocketchat.fullname" .) .Values.serviceAccount.name }}
{{- else -}}
    {{ default "default" .Values.serviceAccount.name }}
{{- end -}}
{{- end -}}

{{/*
Return the apiVersion of deployment.
*/}}
{{- define "deployment.apiVersion" -}}
{{- if semverCompare "<1.14-0" .Capabilities.KubeVersion.GitVersion -}}
{{- print "extensions/v1beta1" -}}
{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}}
{{- print "apps/v1" -}}
{{- end -}}
{{- end -}}
 # deployment.yaml
apiVersion: {{ template "deployment.apiVersion" . }}
kind: Deployment
metadata:
  name: {{ template "rocketchat.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "rocketchat.name" . }}
    helm.sh/chart: {{ include "rocketchat.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "rocketchat.name" . }}
      app.kubernetes.io/instance: {{ .Release.Name }}
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 1
    type: RollingUpdate
  template:
    metadata:
      labels:
        app.kubernetes.io/name: {{ include "rocketchat.name" . }}
        app.kubernetes.io/instance: {{ .Release.Name }}
        {{- if .Values.podLabels }}
{{ toYaml .Values.podLabels | indent 8 }}
        {{- end }}

      annotations:
        checksum/secret: {{ include (print .Template.BasePath "/secret.yaml") . | sha256sum }}
        {{- if .Values.podAnnotations }}
{{ toYaml .Values.podAnnotations | indent 8 }}
        {{- end }}


    spec:
      {{- if .Values.securityContext.enabled }}
      securityContext:
        fsGroup: {{ .Values.securityContext.fsGroup }}
        runAsUser: {{ .Values.securityContext.runAsUser }}
      {{- end }}
      containers:
      - name: rocketchat
        image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
        imagePullPolicy: {{ .Values.image.pullPolicy }}
        env:
        - name: DEPLOY_PLATFORM
          value: helm-chart
        - name: INSTANCE_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        - name: MONGO_URL
          valueFrom:
            secretKeyRef:
              name: {{ template "rocketchat.fullname" . }}
              key: mongo-uri
        - name: MONGO_OPLOG_URL
          valueFrom:
            secretKeyRef:
              name: {{ template "rocketchat.fullname" . }}
              key: mongo-oplog-uri
        {{- if .Values.host }}
        - name: ROOT_URL
          value: https://{{ .Values.host }}
        {{- end }}
        {{- if .Values.smtp.enabled }}
        - name: MAIL_URL
          valueFrom:
            secretKeyRef:
              name: {{ template "rocketchat.fullname" . }}
              key: mail-url
        {{- end }}
{{- with .Values.extraEnv }}
{{ tpl . $ | indent 8 }}
{{- end }}
        ports:
        - name: http
          containerPort: 3000
        {{- if .Values.livenessProbe.enabled }}
        livenessProbe:
          httpGet:
            path: /api/info
            port: http
          initialDelaySeconds: {{ .Values.livenessProbe.initialDelaySeconds }}
          periodSeconds: {{ .Values.livenessProbe.periodSeconds }}
          timeoutSeconds: {{ .Values.livenessProbe.timeoutSeconds }}
          successThreshold: {{ .Values.livenessProbe.successThreshold }}
          failureThreshold: {{ .Values.livenessProbe.failureThreshold }}
        {{- end }}
        {{- if .Values.readinessProbe.enabled }}
        readinessProbe:
          httpGet:
            path: /api/info
            port: http
          initialDelaySeconds: {{ .Values.readinessProbe.initialDelaySeconds }}
          periodSeconds: {{ .Values.readinessProbe.periodSeconds }}
          timeoutSeconds: {{ .Values.readinessProbe.timeoutSeconds }}
          successThreshold: {{ .Values.readinessProbe.successThreshold }}
          failureThreshold: {{ .Values.readinessProbe.failureThreshold }}
        {{- end }}
        resources:
{{ toYaml .Values.resources | indent 10 }}
        volumeMounts:
        - name: rocket-data
          mountPath: /app/uploads
      volumes:
      - name: rocket-data
      {{- if .Values.persistence.enabled }}
        persistentVolumeClaim:
          claimName: {{ if .Values.persistence.existingClaim }}{{ .Values.persistence.existingClaim }}{{- else }}{{ template "rocketchat.fullname" . }}{{- end }}
      {{- else }}
        emptyDir: {}
      {{- end }}
{{- if or .Values.podAntiAffinity .Values.affinity }}
      affinity:
{{- if .Values.affinity }}
{{ toYaml .Values.affinity | indent 8 }}
{{- end }}
{{- if eq .Values.podAntiAffinity "hard" }}
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - topologyKey: {{ .Values.podAntiAffinityTopologyKey }}
            labelSelector:
              matchLabels:
                app.kubernetes.io/name: {{ include "rocketchat.name" . }}
{{- else if eq .Values.podAntiAffinity "soft" }}
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            podAffinityTerm:
              topologyKey: {{ .Values.podAntiAffinityTopologyKey }}
              labelSelector:
                matchLabels:
                  app.kubernetes.io/name: {{ include "rocketchat.name" . }}
                  app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{- end }}
 # ingress.yaml
{{- $ingress := .Values.ingress -}}
{{- if $ingress.enabled -}}
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: {{ template "rocketchat.fullname" . }}
{{- with $ingress.annotations }}
  annotations:
{{ toYaml . | indent 4 }}
{{- end }}
  labels:
    app.kubernetes.io/name: {{ include "rocketchat.name" . }}
    helm.sh/chart: {{ include "rocketchat.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
{{- if $ingress.tls }}
  tls:
  {{- range $ingress.tls }}
    - hosts:
      {{- range .hosts }}
        - {{ . }}
      {{- end }}
      {{- if .secretName }}
      secretName: {{ .secretName }}
      {{- end }}
  {{- end }}
{{- end }}
  rules:
  - host: {{ .Values.host }}
    http:
      paths:
      - path: {{ $ingress.path }}
        backend:
          serviceName: {{ template "rocketchat.fullname" . }}
          servicePort: http
{{- end }}
 # poddisruptionbudget.yaml
{{- if gt ( .Values.replicaCount | int ) 1 }}
apiVersion: policy/v1beta1
kind: PodDisruptionBudget
metadata:
  labels:
    app.kubernetes.io/name: {{ include "rocketchat.name" . }}
    helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  name: {{ template "rocketchat.fullname" . }}
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "rocketchat.name" . }}
      app.kubernetes.io/instance: {{ .Release.Name }}
  minAvailable: {{ .Values.minAvailable }}
{{- end }}
 # pvc.yaml
{{- if .Values.persistence.enabled -}}
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: {{ template "rocketchat.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "rocketchat.name" . }}
    helm.sh/chart: {{ include "rocketchat.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
  accessModes:
    - {{ .Values.persistence.accessMode | quote }}
  resources:
    requests:
      storage: {{ .Values.persistence.size | quote }}
{{- if .Values.persistence.storageClass }}
{{- if (eq "-" .Values.persistence.storageClass) }}
  storageClassName: ""
{{- else }}
  storageClassName: "{{ .Values.persistence.storageClass }}"
{{- end }}
{{- end }}
{{- end -}}
 # secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: {{ template "rocketchat.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "rocketchat.name" . }}
    helm.sh/chart: {{ include "rocketchat.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
type: Opaque
data:
{{- if .Values.smtp.enabled }}
  mail-url: {{ printf "smtp://%s:%s@%s:%.0f" .Values.smtp.username .Values.smtp.password .Values.smtp.host .Values.smtp.port | b64enc | quote }}
{{- end }}
{{- if .Values.externalMongodbUrl }}
  mongo-uri: {{ .Values.externalMongodbUrl | b64enc | quote }}
  mongo-oplog-uri: {{ required "Please specify the external MongoDB OpLog URL" .Values.externalMongodbOplogUrl | b64enc | quote }}
{{- else }}
  {{- $fullname := include "rocketchat.mongodb.fullname" . -}}
  {{- $username := required "Please specify a MongoDB username" .Values.mongodb.mongodbUsername }}
  {{- $password := required "Please specify a MongoDB password" .Values.mongodb.mongodbPassword }}
  {{- $rootPassword := required "Please specify a MongoDB password" .Values.mongodb.mongodbRootPassword }}
  {{- $rsName := .Values.mongodb.replicaSet.name }}
  {{- $port := .Values.mongodb.service.port }}
  {{- $dbname := required "Please specify a MongoDB database" .Values.mongodb.mongodbDatabase }}
  mongo-uri: {{ printf "mongodb://%s:%s@%s:%.0f/%s" $username $password $fullname $port $dbname | b64enc | quote }}
  mongo-oplog-uri: {{ printf "mongodb://root:%s@%s:%.0f/local?replicaSet=%s&authSource=admin" $rootPassword $fullname $port $rsName | b64enc | quote }}
{{- end }}
 # service.yaml
{{- $service := .Values.service -}}
apiVersion: v1
kind: Service
metadata:
  name: {{ template "rocketchat.fullname" . }}
{{- with $service.annotations }}
  annotations:
{{ toYaml . | indent 4 }}
{{- end }}
  labels:
    app.kubernetes.io/name: {{ include "rocketchat.name" . }}
    helm.sh/chart: {{ include "rocketchat.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- with $service.labels }}
{{ toYaml . | indent 4 }}
{{- end }}
spec:
  type: {{ $service.type }}
  ports:
  - name: http
    port: {{ $service.port }}
    targetPort: http
    {{- if and (eq "NodePort" $service.type) $service.nodePort }}
    nodePort: {{ $service.nodePort }}
    {{- end }}
    protocol: TCP
  selector:
    app.kubernetes.io/name: {{ include "rocketchat.name" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
 # serviceaccount.yaml
{{ if .Values.serviceAccount.create }}
apiVersion: v1
kind: ServiceAccount
metadata:
  labels:
    app.kubernetes.io/name: {{ include "rocketchat.name" . }}
    helm.sh/chart: {{ include "rocketchat.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  name: {{ template "rocketchat.serviceAccountName" . }}
{{- end -}}

## Rocket Chat image version
## ref: https://hub.docker.com/r/rocketchat/rocket.chat/tags
##
image:
  repository: docker.io/rocketchat/rocket.chat
  tag: 3.6.0
  pullPolicy: IfNotPresent

## Host for the application
##
# host:

replicaCount: 1
minAvailable: 1

smtp:
  enabled: false
  username:
  password:
  host:
  port: 587

# Extra env vars for Rocket.Chat:
extraEnv:  # |
  # - name: MONGO_OPTIONS
  #   value: '{"ssl": "true"}'
  # - name: MONGO_OPLOG_URL
  #   value: mongodb://oploguser:password@rocket-1:27017/local&replicaSet=rs0

## Pod anti-affinity can prevent the scheduler from placing RocketChat replicas on the same node.
## The default value "soft" means that the scheduler should *prefer* to not schedule two replica pods onto the same node but no guarantee is provided.
## The value "hard" means that the scheduler is *required* to not schedule two replica pods onto the same node.
## The value "" will disable pod anti-affinity so that no anti-affinity rules will be configured.
##
podAntiAffinity: ""

## If anti-affinity is enabled sets the topologyKey to use for anti-affinity.
## This can be changed to, for example, failure-domain.beta.kubernetes.io/zone
##
podAntiAffinityTopologyKey: kubernetes.io/hostname

## Assign custom affinity rules to the RocketChat instance
## ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
##
affinity: {}
# nodeAffinity:
#   requiredDuringSchedulingIgnoredDuringExecution:
#     nodeSelectorTerms:
#     - matchExpressions:
#       - key: kubernetes.io/e2e-az-name
#         operator: In
#         values:
#         - e2e-az1
#         - e2e-az2

## MongoDB URL if using an externally provisioned MongoDB
externalMongodbUrl:  # mongodb://user:password@localhost:27017/rocketchat
externalMongodbOplogUrl:  # mongodb://user:password@localhost:27017/local?replicaSet=rs0&authSource=admin

##
## MongoDB chart configuration
### ref https://github.com/helm/charts/tree/master/stable/mongodb#configuration
##
mongodb:
  ## Enable or disable MongoDB dependency completely.
  enabled: true

  # mongodbRootPassword:

  mongodbUsername: rocketchat
  # mongodbPassword:
  mongodbDatabase: rocketchat

  replicaSet:
    enabled: true
    replicas:
      secondary: 0
      arbiter: 0
    pdb:
      minAvailable:
        secondary: 0
        arbiter: 0

   # key:

  persistence:
    enabled: true
    ## mongodb data Persistent Volume Storage Class
    ## If defined, storageClassName: <storageClass>
    ## If set to "-", storageClassName: "", which disables dynamic provisioning
    ## If undefined (the default) or set to null, no storageClassName spec is
    ##   set, choosing the default provisioner.  (gp2 on AWS, standard on
    ##   GKE, AWS & OpenStack)
    ##
    # storageClass: "-"
    accessMode: ReadWriteOnce
    size: 8Gi

## Enable persistence using Persistent Volume Claims
## ref: http://kubernetes.io/docs/user-guide/persistent-volumes/
##
persistence:
  enabled: false
  # existingClaim: existingClaimName
  ## rocketchat data Persistent Volume Storage Class
  ## If defined, storageClassName: <storageClass>
  ## If set to "-", storageClassName: "", which disables dynamic provisioning
  ## If undefined (the default) or set to null, no storageClassName spec is
  ##   set, choosing the default provisioner.  (gp2 on AWS, standard on
  ##   GKE, AWS & OpenStack)
  ##
  # storageClass: "-"
  accessMode: ReadWriteOnce
  size: 8Gi

## Configure resource requests and limits
## ref: http://kubernetes.io/docs/user-guide/compute-resources/
##
# resources:
#   requests:
#     memory: 512Mi
#     cpu: 300m

securityContext:
  enabled: true
  runAsUser: 999
  fsGroup: 999

serviceAccount:
  # Specifies whether a ServiceAccount should be created
  create: true

  # The name of the ServiceAccount to use.
  # If not set and create is true, a name is generated using the fullname template
  name:

## Configure the ingress object to hook into existing infastructure
### ref : http://kubernetes.io/docs/user-guide/ingress/
###
ingress:
  enabled: false
  annotations: {}
    # kubernetes.io/ingress.class: "nginx"
  path: /
  tls:
  #  - secretName: chart-example-tls
  #    hosts:
  #      - chart-example.local

service:
  annotations: {}
  # service.beta.kubernetes.io/aws-load-balancer-internal: "0.0.0.0/0"

  labels: {}
  # key: value

  ## ServiceType
  ## ref: https://kubernetes.io/docs/user-guide/services/#publishing-services---service-types
  type: ClusterIP

  ## Optional static port assignment for service type NodePort.
  # nodePort: 30000

  port: 80

## Optional Pod Labels.
podLabels: {}

## Optional Pod Annotations.
podAnnotations: {}
  # prometheus.io/port: "9458"
  # prometheus.io/path: "/metrics"
  # prometheus.io/scrape: "true"

## Liveness and readiness probe values
## Ref: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes
##
livenessProbe:
  enabled: true
  initialDelaySeconds: 60
  periodSeconds: 15
  timeoutSeconds: 5
  failureThreshold: 3
  successThreshold: 1

readinessProbe:
  enabled: true
  initialDelaySeconds: 10
  periodSeconds: 15
  timeoutSeconds: 5
  failureThreshold: 3
  successThreshold: 1
