{{- if .Values.dashboardImport.dashboards }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "kibana.fullname" . }}-importscript
  labels:
    app: {{ template "kibana.name" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
data:
  dashboardImport.sh: |
    #!/usr/bin/env bash
    #
    # kibana dashboard import script
    #

    cd /kibanadashboards

    echo "Starting Kibana..."

    /usr/local/bin/kibana-docker $@ &

    echo "Waiting up to {{ .Values.dashboardImport.timeout }} seconds for Kibana to get in green overall state..."

    for i in {1..{{ .Values.dashboardImport.timeout }}}; do
      curl -s localhost:5601/api/status | python -c 'import sys, json; print json.load(sys.stdin)["status"]["overall"]["state"]' 2> /dev/null | grep green > /dev/null && break || sleep 1
    done

    for DASHBOARD_FILE in *; do
      echo -e "Importing ${DASHBOARD_FILE} dashboard..."

      if ! python -c 'import sys, json; print json.load(sys.stdin)' < "${DASHBOARD_FILE}" &> /dev/null ; then
        echo "${DASHBOARD_FILE} is not valid JSON, assuming it's an URL..."
        TMP_FILE="$(mktemp)"
        curl -s $(cat ${DASHBOARD_FILE}) > ${TMP_FILE}
        curl -v {{ if .Values.dashboardImport.xpackauth.enabled }}--user {{ .Values.dashboardImport.xpackauth.username }}:{{ .Values.dashboardImport.xpackauth.password }}{{ end }} -s --connect-timeout 60 --max-time 60 -XPOST localhost:5601/api/kibana/dashboards/import?force=true -H 'kbn-xsrf:true' -H 'Content-type:application/json' -d @${TMP_FILE}
        rm ${TMP_FILE}
      else
        echo "Valid JSON found in ${DASHBOARD_FILE}, importing..."
        curl -v {{ if .Values.dashboardImport.xpackauth.enabled }}--user {{ .Values.dashboardImport.xpackauth.username }}:{{ .Values.dashboardImport.xpackauth.password }}{{ end }} -s --connect-timeout 60 --max-time 60 -XPOST localhost:5601/api/kibana/dashboards/import?force=true -H 'kbn-xsrf:true' -H 'Content-type:application/json' -d @./${DASHBOARD_FILE}
      fi

      if [ "$?" != "0" ]; then
        echo -e "\nImport of ${DASHBOARD_FILE} dashboard failed... Exiting..."
        exit 1
      else
        echo -e "\nImport of ${DASHBOARD_FILE} dashboard finished :-)"
      fi

    done
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "kibana.fullname" . }}-dashboards
  labels:
    app: {{ template "kibana.name" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
data:
{{- range $key, $value := .Values.dashboardImport.dashboards }}
  {{ $key }}: |-
{{ $value | indent 4 }}
{{- end -}}
{{- end -}}
