{{- if and .Values.alertmanager.enabled .Values.alertmanager.servicePerReplica.enabled }}
{{- $count := .Values.alertmanager.alertmanagerSpec.replicas | int -}}
{{- $serviceValues := .Values.alertmanager.servicePerReplica -}}
apiVersion: v1
kind: List
metadata:
  name: {{ include "kube-prometheus-stack.fullname" $ }}-alertmanager-serviceperreplica
  namespace: {{ template "kube-prometheus-stack.namespace" . }}
items:
{{- range $i, $e := until $count }}
  - apiVersion: v1
    kind: Service
    metadata:
      name: {{ include "kube-prometheus-stack.fullname" $ }}-alertmanager-{{ $i }}
      namespace: {{ template "kube-prometheus-stack.namespace" $ }}
      labels:
        app: {{ include "kube-prometheus-stack.name" $ }}-alertmanager
{{ include "kube-prometheus-stack.labels" $ | indent 8 }}
      {{- if $serviceValues.annotations }}
      annotations:
{{ toYaml $serviceValues.annotations | indent 8 }}
      {{- end }}
    spec:
      {{- if $serviceValues.clusterIP }}
      clusterIP: {{ $serviceValues.clusterIP }}
      {{- end }}
      {{- if $serviceValues.loadBalancerSourceRanges }}
      loadBalancerSourceRanges:
      {{- range $cidr := $serviceValues.loadBalancerSourceRanges }}
        - {{ $cidr }}
      {{- end }}
      {{- end }}
      {{- if ne $serviceValues.type "ClusterIP" }}
      externalTrafficPolicy: {{ $serviceValues.externalTrafficPolicy }}
      {{- end }}
      ports:
        - name: {{ $.Values.alertmanager.alertmanagerSpec.portName }}
          {{- if eq $serviceValues.type "NodePort" }}
          nodePort: {{ $serviceValues.nodePort }}
          {{- end }}
          port: {{ $serviceValues.port }}
          targetPort: {{ $serviceValues.targetPort }}
      selector:
        app.kubernetes.io/name: alertmanager
        alertmanager: {{ template "kube-prometheus-stack.alertmanager.crname" $ }}
        statefulset.kubernetes.io/pod-name: alertmanager-{{ include "kube-prometheus-stack.alertmanager.crname" $ }}-{{ $i }}
      type: "{{ $serviceValues.type }}"
{{- end }}
{{- end }}
