{{- if and .Values.metrics.enabled .Values.metrics.serviceMonitor.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: {{ template "vault-secrets-webhook.fullname" . }}
  namespace: {{ .Release.Namespace }}
  labels:
    helm.sh/chart: {{ template "vault-secrets-webhook.chart" . }}
    app.kubernetes.io/name: {{ template "vault-secrets-webhook.name" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
    app.kubernetes.io/component: mutating-webhook
    {{- if .Values.metrics.serviceMonitor.additionalLabels }}
{{ toYaml .Values.metrics.serviceMonitor.additionalLabels | indent 4 }}
    {{- end }}
spec:
  endpoints:
  - interval: 30s
    port: metrics
    scheme: {{ .Values.metrics.serviceMonitor.scheme }}
    {{- if .Values.metrics.serviceMonitor.relabellings }}
    metricrelabelings:
{{ toYaml .Values.metrics.serviceMonitor.relabellings | indent 6 }}
    {{- end }}
    {{- if .Values.metrics.serviceMonitor.tlsConfig }}
    tlsConfig:
{{ toYaml .Values.metrics.serviceMonitor.tlsConfig | indent 6 }}
    {{- end }}
  jobLabel: {{ template "vault-secrets-webhook.name" . }}
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ template "vault-secrets-webhook.name" . }}
      app.kubernetes.io/instance: "{{ .Release.Name }}"
{{- end }}
{{- if .Values.metrics.enabled }}
---
apiVersion: v1
kind: Service
metadata:
  annotations:
  name: {{ template "vault-secrets-webhook.fullname" . }}-metrics
  namespace: {{ .Release.Namespace }}
  labels:
    helm.sh/chart: {{ template "vault-secrets-webhook.chart" . }}
    app.kubernetes.io/name: {{ template "vault-secrets-webhook.name" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
    app.kubernetes.io/component: mutating-webhook
spec:
  clusterIP: None
  ports:
  - name: metrics
    port: {{ .Values.metrics.port }}
    protocol: TCP
    targetPort: {{ .Values.metrics.port }}
  selector:
    app.kubernetes.io/name: {{ template "vault-secrets-webhook.name" . }}
    app.kubernetes.io/instance: "{{ .Release.Name }}"
  sessionAffinity: None
  type: ClusterIP
{{- end }}
