#!/bin/bash

{{/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/}}

set -ex

source /tmp/osd-common-ceph-volume.sh

# This script will execute a series of:
#   ceph config set <section> <key> <value>
# for values defined in .Values.conf.ceph
#
# .Values.conf.ceph is expected to be a map where each key is the section name:
# Example values structure (Helm values.yaml):
# conf:
#   ceph:
#     osd:
#       debug_osd: 10
#     mon:
#       debug_mon: 20

# helper: run a ceph config set and log the command
run_ceph_set() {
    echo "+ ceph config set $1 $2 $3"
    timeout 10 ceph --name client.bootstrap-osd --keyring ${OSD_BOOTSTRAP_KEYRING} config set "$1" "$2" "$3"
}

# Disable exit on error to ignore config set failures
set +e

# The following block is generated by Helm templating and will expand into
# concrete ceph config set commands. Do not edit at runtime.

{{- /* Iterate sections (keys are section names). Sections must not contain nested maps. */ -}}
{{- if .Values.conf.ceph }}
{{- range $secName, $secValues := .Values.conf.ceph }}
echo "Applying Ceph config for section: {{ $secName }}"
{{- if eq (kindOf $secValues) "map" }}
  {{- range $k, $v := $secValues }}
    {{- if eq (kindOf $v) "map" }}
echo "ERROR: nested maps are not allowed in section '{{ $secName }}' for key '{{ $k }}'. Aborting."
exit 1
    {{- else }}
run_ceph_set {{ $secName }} {{ $k }} {{ $v | quote }}
    {{- end }}
  {{- end }}
{{- else }}
echo "ERROR: section '{{ $secName }}' is not a valid map. Aborting.
exit 1
{{- end }}
{{- end }}
{{- else }}
echo "No .Values.conf.ceph defined, nothing to configure."
{{- end -}}

exit 0
