{{- if and .Values.replication.enabled .Values.replication.uniqueServices }}
{{- $serviceAnnotations := coalesce .Values.readReplicas.service.annotations .Values.service.annotations -}}

{{- $fullName := include "common.names.fullname" . }}
{{- $replicaCount := .Values.replication.readReplicas | int }}
{{- $root := . }}

{{- range $i, $e := until $replicaCount }}
{{- $targetPod := printf "%s-read-%d" (printf "%s" $fullName) $i }}
---
apiVersion: v1
kind: Service
metadata:
  name: {{ $fullName }}-read-{{ $i }}
  labels:
    pod: {{ $targetPod }}
  {{- include "common.labels.standard" $root | nindent 4 }}
  annotations:

  {{- if $root.Values.commonAnnotations }}
  {{- include "common.tplvalues.render" ( dict "value" $root.Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
  {{- if $serviceAnnotations }}
  {{- include "common.tplvalues.render" (dict "value" $serviceAnnotations "context" $) | nindent 4 }}
  {{- end }}
  namespace: {{ $root.Release.Namespace }}
spec:
  type: ClusterIP
  ports:
    - name: tcp-postgresql
      port:  {{ template "postgresql.port" $root }}
      targetPort: tcp-postgresql
  selector:
  {{- include "common.labels.matchLabels" $root | nindent 4 }}
    role: read
    statefulset.kubernetes.io/pod-name: {{ $targetPod }}

{{- end }}
{{- end }}