{{- /*
Copyright Broadcom, Inc. All Rights Reserved.
SPDX-License-Identifier: APACHE-2.0
*/}}

{{- if (include "kibana.importSavedObjects" .) -}}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ printf "%s-saved-objects" (include "common.names.fullname" .) }}
  namespace: {{ include "common.names.namespace" . | quote }}
  labels: {{- include "common.labels.standard" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 4 }}
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
data:
  {{- $savedObjectsUrl := printf "%s://%s:%d%s/api/saved_objects/_import%s" (ternary "https" "http" .Values.tls.enabled) (include "common.names.fullname" .) (int .Values.containerPorts.http) (include "kibana.basePath" .) (ternary "?overwrite=true" "" .Values.savedObjects.overwrite) }}
  import-saved-objects.sh: |
    #!/bin/bash
    echo "==> Saved objects import"
    CURL_TLS_FLAGS=""
    CURL_AUTH_FLAGS=""

    {{- if .Values.tls.enabled }}
    CURL_TLS_FLAGS="--cacert /opt/bitnami/kibana/config/certs/server/ca.crt"
    {{- end }}


    {{- if .Values.elasticsearch.security.auth.enabled }}
    {{- if .Values.usePasswordFiles }}
    if [[ -f "/opt/bitnami/kibana/secrets/kibana-password" ]]; then
      KIBANA_PASSWORD=$(< "/opt/bitnami/kibana/secrets/kibana-password" tr -d '\n')
      CURL_AUTH_FLAGS="-u elastic:${KIBANA_PASSWORD}"
    else
      echo "ERROR: kibana-password file NOT found at /opt/bitnami/kibana/secrets/"
    fi
    {{- else }}
    CURL_AUTH_FLAGS="-u elastic:${KIBANA_PASSWORD}"
    {{- end }}
    {{- end }}

    {{- if .Values.savedObjects.urls }}
    {{- $totalURLs := len .Values.savedObjects.urls }}
    echo "Total saved objects NDJSON URLs to import: {{ $totalURLs }}"
    {{- range $i, $url := .Values.savedObjects.urls }}
    echo "Importing saved objects from NDJSON in url {{ add $i 1 }} out of {{ $totalURLs }}: {{ $url }}"
    download_tmp_file="$(mktemp)"
    curl "{{ $url }}" > "${download_tmp_file}.ndjson"
    curl -s --connect-timeout 60 --max-time 60 -XPOST {{ $savedObjectsUrl }} -H 'kbn-xsrf:true' --form file=@"${download_tmp_file}.ndjson" ${CURL_TLS_FLAGS} ${CURL_AUTH_FLAGS}
    {{- end }}
    {{- end }}
    {{- if .Values.savedObjects.configmap }}
    echo "Searching for dashboard NDJSON files from ConfigMap mounted in /bitnami/kibana/saved-objects"
    ndjson_file_list_tmp="$(mktemp)"
    find /bitnami/kibana/saved-objects -type f -regex ".*\.ndjson" > $ndjson_file_list_tmp
    while read -r f; do
      case "$f" in
        *.ndjson)
          echo "Importing $f"
          curl -s --connect-timeout 60 --max-time 60 -XPOST {{ $savedObjectsUrl }} -H 'kbn-xsrf:true' --form file=@"${f}" ${CURL_TLS_FLAGS} ${CURL_AUTH_FLAGS}
          ;;
        *)
          echo "Ignoring $f"
          ;;
      esac
    done < $ndjson_file_list_tmp
    {{- end }}
    echo "==> End of Saved objects import"
{{- end -}}
