{{- if and .Values.prometheus.thanosService.enabled .Values.prometheus.thanosServiceMonitor.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: {{ template "kube-prometheus-stack.fullname" . }}-thanos-sidecar
  namespace: {{ template "kube-prometheus-stack.namespace" . }}
  labels:
    app: {{ template "kube-prometheus-stack.name" . }}-thanos-sidecar
{{ include "kube-prometheus-stack.labels" . | indent 4 }}
{{- with .Values.prometheus.thanosServiceMonitor.additionalLabels }}
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
  {{- include "servicemonitor.scrapeLimits" .Values.prometheus.thanosServiceMonitor | nindent 2 }}
  selector:
    matchLabels:
      app: {{ template "kube-prometheus-stack.name" . }}-thanos-discovery
      release: {{ $.Release.Name | quote }}
  namespaceSelector:
    matchNames:
      - {{ printf "%s" (include "kube-prometheus-stack.namespace" .) | quote }}
  endpoints:
  - port: {{ .Values.prometheus.thanosService.httpPortName }}
    {{- if .Values.prometheus.thanosServiceMonitor.interval }}
    interval: {{ .Values.prometheus.thanosServiceMonitor.interval }}
    {{- end }}
    {{- if .Values.prometheus.thanosServiceMonitor.scheme }}
    scheme: {{ .Values.prometheus.thanosServiceMonitor.scheme }}
    {{- end }}
    {{- if .Values.prometheus.thanosServiceMonitor.tlsConfig }}
    tlsConfig: {{ toYaml .Values.prometheus.thanosServiceMonitor.tlsConfig | nindent 6 }}
    {{- end }}
    {{- if .Values.prometheus.thanosServiceMonitor.bearerTokenFile }}
    bearerTokenFile: {{ .Values.prometheus.thanosServiceMonitor.bearerTokenFile }}
    {{- end }}
    path: "/metrics"
    metricRelabelings:
    {{- if .Values.prometheus.thanosServiceMonitor.metricRelabelings}}
    {{ tpl (toYaml .Values.prometheus.thanosServiceMonitor.metricRelabelings | indent 6) . }}
    {{- end }}
    {{ if .Values.global.cattle.clusterId }}
      - sourceLabels: [__address__]
        targetLabel: cluster_id
        replacement: {{ .Values.global.cattle.clusterId }}
    {{- end }}
    {{ if .Values.global.cattle.clusterName}}
      - sourceLabels: [__address__]
        targetLabel: cluster_name
        replacement: {{ .Values.global.cattle.clusterName }}
    {{- end }}
{{- if .Values.prometheus.thanosServiceMonitor.relabelings }}
    relabelings:
{{ toYaml .Values.prometheus.thanosServiceMonitor.relabelings | indent 6 }}
{{- end }}
{{- end }}
