- name: Create SG-specific Service Monitor manifest
  set_fact:
    sg_specific_servicemonitor_manifest: |
      apiVersion: monitoring.coreos.com/v1
      kind: ServiceMonitor
      metadata:
        labels:
          app: smart-gateway
        name: '{{ this_smartgateway }}'
        namespace: '{{ meta.namespace }}'
      spec:
        endpoints:
          - interval: {{ servicetelemetry_vars.backends.metrics.prometheus.scrape_interval }}
            metricRelabelings:
              - action: labeldrop
                regex: pod
                sourcelabels: []
              - action: labeldrop
                regex: namespace
                sourcelabels: []
              - action: labeldrop
                regex: instance
                sourcelabels: []
              - action: labeldrop
                regex: job
                sourcelabels: []
              - action: labeldrop
                regex: publisher
                sourcelabels: []
            port: prom-https
            scheme: https
            tlsConfig:
              caFile: /etc/prometheus/configmaps/serving-certs-ca-bundle/service-ca.crt
              serverName: "{{ this_smartgateway }}.{{ meta.namespace }}.svc"
            bearerTokenFile: /var/run/secrets/kubernetes.io/serviceaccount/token
        selector:
          matchLabels:
            app: smart-gateway
            smart-gateway: "{{ this_smartgateway }}"

- name: Create ServiceMonitor to scrape Smart Gateway
  k8s:
    state: '{{ "present" if servicetelemetry_vars.backends.metrics.prometheus.enabled else "absent" }}'
    definition:
      '{{ sg_specific_servicemonitor_manifest }}'

- name: Create additional serviceMonitor if provided
  k8s:
    state: '{{ "present" if servicetelemetry_vars.backends.metrics.prometheus.enabled else "absent" }}'
    definition:
      '{{ servicemonitor_manifest }}'
  when: servicemonitor_manifest is defined
