{{- if .Values.metrics.enabled -}}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "common.names.fullname" . }}-metrics-scripts
  namespace: {{ .Release.Namespace }}
  labels: {{- include "common.labels.standard" . | nindent 4 }}
    app.kubernetes.io/component: server
    {{- if .Values.commonLabels }}
    {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }}
    {{- end }}
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
data:
  enable-metrics-plugin.sh: |-
    #!/bin/bash
    . /opt/bitnami/scripts/libos.sh
    . /opt/bitnami/scripts/libkong.sh

    info "Enabling prometheus plugin"

    if curl --silent http://localhost:{{ .Values.kong.containerPorts.adminHttp }}/ | grep -Eo '"prometheus":false' > /dev/null; then
      if ! curl --silent http://localhost:{{ .Values.kong.containerPorts.adminHttp }}/plugins -d name=prometheus; then
         info "Issue enabling prometheus plugin, this could be due to a race condition with another kong node. Checking status"
      fi
      if curl http://localhost:{{ .Values.kong.containerPorts.adminHttp }}/ | grep -Eo '"prometheus":true' > /dev/null; then
         info "Prometheus metrics plugin enabled"
      else
         error "Error enabling Prometheus plugin"
         exit 1
      fi
    else
      info "Prometheus plugin already enabled"
    fi
{{- end }}
