apiVersion: v1
kind: Secret
metadata:
  name: {{ include "keydb.fullname" . }}-utils
  labels:
    {{- include "keydb.labels" . | nindent 4 }}
type: Opaque
stringData:
  server.sh: |
    #!/bin/bash
    set -euxo pipefail

    host="$(hostname)"
    replicas=()
    for node in {0..{{ (sub (.Values.nodes | int) 1) }}}; do
      if [ "${host}" != "{{ include "keydb.fullname" . }}-${node}" ]; then
          replicas+=("--replicaof {{ include "keydb.fullname" . }}-${node}.{{ include "keydb.fullname" . }}-headless {{ .Values.port }}")
      fi
    done
    exec keydb-server /etc/keydb/redis.conf \
        --active-replica {{ .Values.activeReplicas | quote }} \
        --multi-master {{ .Values.multiMaster | quote }} \
        --appendonly {{ .Values.appendonly | quote }} \
        --bind "0.0.0.0" \
        --port "{{ .Values.internalPort }}" \
        --protected-mode {{ .Values.protectedMode | quote }} \
        --server-threads {{ .Values.threads | quote }} \
        {{- if .Values.existingSecret }}
        --masterauth "${REDIS_PASSWORD}" \
        --requirepass "${REDIS_PASSWORD}" \
        {{- else if .Values.password }}
        --masterauth {{ .Values.password | quote }} \
        --requirepass {{ .Values.password | quote }} \
        {{- end }}
        {{- range $item := .Values.configExtraArgs }}
        {{- range $key, $value := $item }}
        {{- if kindIs "invalid" $value }}
        --{{ $key }} \
        {{- else if kindIs "slice" $value }}
        --{{ $key }}{{ range $value }} {{ . | quote }}{{ end }} \
        {{- else }}
        --{{ $key }} {{ $value | quote }} \
        {{- end }}
        {{- end }}
        {{- end }}
        "${replicas[@]}"
