{{- if .Values.service.internal -}}

{{- $fullname := include "traefik.fullname" . }}
{{- if ge (len $fullname) 50 }}
  {{- fail "ERROR: Cannot create an internal service when name contains more than 50 characters" }}
{{- end }}

{{- $tcpPorts := dict -}}
{{- $udpPorts := dict -}}
{{- $exposedPorts := false -}}
{{- range $name, $config := .Values.ports -}}
  {{- if eq (toString $config.protocol) "UDP" -}}
    {{ $_ := set $udpPorts $name $config -}}
  {{- end -}}
  {{- if eq (toString (default "TCP" $config.protocol)) "TCP" -}}
    {{ $_ := set $tcpPorts $name $config -}}
  {{- end -}}
{{- end -}}

{{- if (or $tcpPorts .Values.service.single) }}
apiVersion: v1
kind: Service
metadata:
  name: {{ $fullname}}-internal
  namespace: {{ template "traefik.namespace" . }}
  {{- template "traefik.service-internal-metadata" . }}
  annotations:
  {{- with .Values.service.internal.annotations }}
  {{- toYaml . | nindent 4 }}
  {{- end }}
spec:
  {{- template "traefik.service-internal-spec" . }}
  ports:
  {{- template "traefik.service-internal-ports" $tcpPorts }}
{{- if .Values.service.single }}
  {{- template "traefik.service-internal-ports" $udpPorts }}
{{- end }}
{{- end }}

{{- if (and $udpPorts (not .Values.service.single)) }}
---
apiVersion: v1
kind: Service
metadata:
  name: {{ $fullname }}-internal-udp
  namespace: {{ template "traefik.namespace" . }}
  {{- template "traefik.service-internal-metadata" . }}
  annotations:
  {{- with .Values.service.internal.annotations }}
  {{- toYaml . | nindent 4 }}
  {{- end }}
spec:
  {{- template "traefik.service-internal-spec" . }}
  ports:
  {{- template "traefik.service-internal-ports" $udpPorts }}
{{- end }}

{{- end -}}
