{{- if .Values.topics -}}
{{- $zk := include "zookeeper.url" . -}}
apiVersion: v1
kind: ConfigMap
metadata:
  labels:
    app: {{ template "kafka.fullname" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    heritage: "{{ .Release.Service }}"
    release: "{{ .Release.Name }}"
  name: {{ template "kafka.fullname" . }}-config
data:
  runtimeConfig.sh: |
    #!/bin/sh
    set -e
    cd /usr/bin
    until kafka-configs --zookeeper {{ $zk }} --entity-type topics --describe || (( count++ >= 6 ))
    do
      echo "Waiting for Zookeeper..."
      sleep 20
    done
    echo "Applying runtime configuration using {{ .Values.image }}:{{ .Values.imageTag }}"
    {{- range $n, $topic := .Values.topics }}
    {{- if and $topic.partitions $topic.replicationFactor }}
    kafka-topics --zookeeper {{ $zk }} --create --if-not-exists --force --topic {{ $topic.name }} --partitions {{ $topic.partitions }} --replication-factor {{ $topic.replicationFactor }}
    {{- else if $topic.partitions }}
    kafka-topics --zookeeper {{ $zk }} --alter --force --topic {{ $topic.name }} --partitions {{ $topic.partitions }} || true
    {{- end }}
    {{- if $topic.defaultConfig }}
    kafka-configs --zookeeper {{ $zk }} --entity-type topics --entity-name {{ $topic.name }} --alter --force --delete-config {{ nospace $topic.defaultConfig }} || true
    {{- end }}
    {{- if $topic.config }}
    kafka-configs --zookeeper {{ $zk }} --entity-type topics --entity-name {{ $topic.name }} --alter --force --add-config {{ nospace $topic.config }}
    {{- end }}
    kafka-configs --zookeeper {{ $zk }} --entity-type topics --entity-name {{ $topic.name }} --describe
    {{- end }}
{{- end -}}
