{{- if .Values.controlPlane.serviceMonitor.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: vc-{{ .Release.Name }}
  namespace: {{ .Release.Namespace }}
  labels:
    app: vcluster
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
  {{- if or (not .Values.controlPlane.serviceMonitor.labels) (not (hasKey .Values.controlPlane.serviceMonitor.labels "release")) }}
    release: "{{ .Release.Name }}"
  {{- end}}
    heritage: "{{ .Release.Service }}"
  {{- if .Values.controlPlane.serviceMonitor.labels }}
{{ toYaml .Values.controlPlane.serviceMonitor.labels | indent 4 }}
  {{- end }}
  {{- $annotations := merge dict .Values.controlPlane.serviceMonitor.annotations .Values.controlPlane.advanced.globalMetadata.annotations }}
  {{- if $annotations }}
  annotations:
{{ toYaml $annotations | indent 4 }}
  {{- end }}
spec:
  selector:
    matchLabels:
      app: vcluster
      release: "{{ .Release.Name }}"
      chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
      heritage: "{{ .Release.Service }}"
      vcluster.loft.sh/service: "true"
  endpoints:
  - interval: 30s
    port: https
    path: /metrics
    scheme: https
    relabelings:
      - targetLabel: endpoint
        replacement: "apiserver"
    tlsConfig:
      ca:
        secret:
          name: vc-{{ .Release.Name }}
          key: certificate-authority
      cert:
        secret:
          name: vc-{{ .Release.Name }}
          key: client-certificate
      keySecret:
        name: vc-{{ .Release.Name }}
        key: client-key
  {{- if eq (include "vcluster.distro" .) "k8s" }}
  - interval: 30s
    port: https
    path: /controller-manager/metrics
    scheme: https
    relabelings:
      - targetLabel: endpoint
        replacement: "controller-manager"
    tlsConfig:
      ca:
        secret:
          name: vc-{{ .Release.Name }}
          key: certificate-authority
      cert:
        secret:
          name: vc-{{ .Release.Name }}
          key: client-certificate
      keySecret:
        name: vc-{{ .Release.Name }}
        key: client-key
  {{- if or
      (and (eq (include "vcluster.distro" .) "k8s") .Values.controlPlane.distro.k8s.scheduler.enabled)
      .Values.controlPlane.advanced.virtualScheduler.enabled
      }}
  - interval: 30s
    port: https
    path: /scheduler/metrics
    scheme: https
    relabelings:
      - targetLabel: endpoint
        replacement: "scheduler"
    tlsConfig:
      ca:
        secret:
          name: vc-{{ .Release.Name }}
          key: certificate-authority
      cert:
        secret:
          name: vc-{{ .Release.Name }}
          key: client-certificate
      keySecret:
        name: vc-{{ .Release.Name }}
        key: client-key
  {{- end }}
  {{- end }}
{{- end }}
