{{- $apiVersion := include "argo-workflows.apiVersions.monitoring" . }}
{{- if and (.Capabilities.APIVersions.Has $apiVersion) (or .Values.controller.metricsConfig.enabled .Values.controller.telemetryConfig.enabled) .Values.controller.serviceMonitor.enabled }}
apiVersion: {{ $apiVersion }}
kind: ServiceMonitor
metadata:
  name: {{ template "argo-workflows.controller.fullname" . }}
  namespace: {{ default (include "argo-workflows.namespace" .) .Values.controller.serviceMonitor.namespace | quote }}
  labels:
    {{- include "argo-workflows.labels" (dict "context" . "component" .Values.controller.name "name" .Values.controller.name) | nindent 4 }}
    {{- with .Values.controller.serviceMonitor.additionalLabels }}
      {{- toYaml . | nindent 4 }}
    {{- end }}
spec:
  endpoints:
  {{- if .Values.controller.metricsConfig.enabled }}
    - port: {{ .Values.controller.metricsConfig.servicePortName }}
      path: {{ .Values.controller.metricsConfig.path }}
      interval: {{ .Values.controller.metricsConfig.interval }}
      {{- with .Values.controller.metricsConfig.relabelings }}
      relabelings:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.controller.metricsConfig.metricRelabelings }}
      metricRelabelings:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      honorLabels: {{ .Values.controller.metricsConfig.honorLabels }}
  {{- end }}
  {{- if .Values.controller.telemetryConfig.enabled }}
    - port: telemetry
      path: {{ .Values.controller.telemetryConfig.path }}
      interval: {{ .Values.controller.telemetryConfig.interval }}
      {{- with .Values.controller.metricsConfig.relabelings }}
      relabelings:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.controller.metricsConfig.metricRelabelings }}
      metricRelabelings:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      honorLabels: {{ .Values.controller.metricsConfig.honorLabels }}
  {{- end }}
  {{- with .Values.controller.metricsConfig.targetLabels }}
  targetLabels:
    {{- toYaml . | nindent 8 }}
  {{- end }}
  namespaceSelector:
    matchNames:
      - {{ include "argo-workflows.namespace" . | quote }}
  selector:
    matchLabels:
      {{- include "argo-workflows.selectorLabels" (dict "context" . "name" .Values.controller.name) | nindent 6 }}
{{- end }}
