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

{{- if and .Values.metrics.enabled .Values.metrics.serviceMonitor.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: {{ template "common.names.fullname" . }}
  namespace: {{ default (include "common.names.namespace" .) .Values.metrics.serviceMonitor.namespace }}
  {{- $labels := include "common.tplvalues.merge" ( dict "values" ( list .Values.metrics.serviceMonitor.labels .Values.commonLabels ) "context" . ) }}
  labels: {{- include "common.labels.standard" ( dict "customLabels" $labels "context" $ ) | nindent 4 }}
    app.kubernetes.io/component: kubernetes-event-exporter
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
spec:
  {{- if .Values.metrics.serviceMonitor.jobLabel }}
  jobLabel: {{ .Values.metrics.serviceMonitor.jobLabel }}
  {{- end }}
  endpoints:
    {{- $defaultEndpoint := pick .Values.metrics.serviceMonitor "port" "interval" "scrapeTimeout" "relabelings" "metricRelabelings" "honorLabels" }}
    {{- $endpoints := ternary (.Values.metrics.serviceMonitor.endpoints) (list (dict "path" .Values.metrics.serviceMonitor.path)) (empty .Values.metrics.serviceMonitor.path) }}
    {{- range $endpoints }}
    {{- $endpoint := merge . $defaultEndpoint }}
    - port: {{ $endpoint.port }}
      path: {{ $endpoint.path }}
      {{- if $endpoint.interval }}
      interval: {{ $endpoint.interval }}
      {{- end }}
      {{- if $endpoint.scrapeTimeout }}
      scrapeTimeout: {{ $endpoint.scrapeTimeout }}
      {{- end }}
      {{- if $endpoint.relabelings }}
      relabelings: {{- include "common.tplvalues.render" ( dict "value" $endpoint.relabelings "context" $) | nindent 6 }}
      {{- end }}
      {{- if $endpoint.metricRelabelings }}
      metricRelabelings: {{- include "common.tplvalues.render" ( dict "value" $endpoint.metricRelabelings "context" $) | nindent 6 }}
      {{- end }}
      {{- if $endpoint.honorLabels }}
      honorLabels: {{ $endpoint.honorLabels }}
      {{- end }}
    {{- end }}
  namespaceSelector:
    matchNames:
      - {{ include "common.names.namespace" . | quote }}
  selector:
    matchLabels: {{- include "common.labels.matchLabels" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 6 }}
      {{- if .Values.metrics.serviceMonitor.selector }}
      {{- include "common.tplvalues.render" (dict "value" .Values.metrics.serviceMonitor.selector "context" $) | nindent 6 }}
      {{- end }}
      app.kubernetes.io/component: metrics
{{- end }}
