{{- 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.labels.standard" . | nindent 4 }}
    app.kubernetes.io/component: kubernetes-event-exporter
    {{- if .Values.metrics.serviceMonitor.labels }}
    {{- include "common.tplvalues.render" (dict "value" .Values.metrics.serviceMonitor.labels "context" $) | nindent 4 }}
    {{- end }}
    {{- 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 }}
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" . | 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 }}
