{{- $highAvailability := gt (int .Values.keycloak.replicas) 1 -}}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "keycloak.fullname" . }}
  labels:
    app: {{ template "keycloak.name" . }}
    chart: {{ template "keycloak.chart" . }}
    release: "{{ .Release.Name }}"
    heritage: "{{ .Release.Service }}"
data:
  keycloak.sh: |
    #!/usr/bin/env bash

    set -eu

    /opt/jboss/keycloak/bin/jboss-cli.sh --file=/scripts/keycloak.cli

  {{- with .Values.keycloak.preStartScript }}
    echo 'Running custom pre-start script...'
{{ . | indent 4 }}
  {{- end }}

    exec /opt/jboss/docker-entrypoint.sh -b 0.0.0.0 {{ .Values.keycloak.extraArgs }}{{- if $highAvailability }} --server-config standalone-ha.xml{{ end }}
    exit "$?"

  keycloak.cli: |
    embed-server {{- if $highAvailability }} --server-config=standalone-ha.xml{{ end }} --std-out=echo

{{- with .Values.keycloak.cli }}

{{ .nodeIdentifier | indent 4 }}

{{ .logging | indent 4 }}

{{ .reverseProxy | indent 4 }}

{{- if $highAvailability }}
{{ .discovery | indent 4 }}
{{- end }}

{{- if and $highAvailability (eq $.Values.keycloak.persistence.dbVendor "postgres") }}
{{ .postgresql | indent 4 }}
{{- end }}

{{- with .custom }}
{{ . | indent 4 }}
{{- end }}

{{- end }}

    stop-embedded-server
