{{- if .Values.service.enabled -}}
apiVersion: v1
kind: Service
metadata:
  name: {{ include "telegraf.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "telegraf.name" . }}
    helm.sh/chart: {{ include "telegraf.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  {{- if .Values.service.annotations }}
  annotations:
{{ toYaml .Values.service.annotations | indent 4 }}
  {{- end }}
spec:
  type: {{ .Values.service.type }}
  ports:
  {{- range $objectKey, $objectValue := .Values.config.outputs }}
  {{- range $key, $value := . -}}
  {{- $tp := typeOf $value -}}
  {{- if eq $key "health" }}
  - port: {{ trimPrefix "http://:" $value.service_address | int64 }}
    targetPort: {{ trimPrefix "http://:" $value.service_address | int64 }}
    name: "health"
    {{- end }}
  {{- end }}
  {{- end }}
  {{- range $objectKey, $objectValue := .Values.config.inputs }}
  {{- range $key, $value := . -}}
    {{- $tp := typeOf $value -}}
    {{- if eq $key "http_listener" }}
  - port: {{ trimPrefix ":" $value.service_address | int64 }}
    targetPort: {{ trimPrefix ":" $value.service_address | int64 }}
    name: "http-listener"
    {{- end }}
    {{- if eq $key "statsd" }}
  - port: {{ trimPrefix ":" $value.service_address | int64 }}
    targetPort: {{ trimPrefix ":" $value.service_address | int64 }}
    protocol: "UDP"
    name: "statsd"
    {{- end }}
    {{- if eq $key "tcp-listener" }}
  - port: {{ trimPrefix ":" $value.service_address | int64 }}
    targetPort: {{ trimPrefix ":" $value.service_address | int64 }}
    name: "tcp_listener"
    {{- end }}
    {{- if eq $key "udp-listener" }}
  - port: {{ trimPrefix ":" $value.service_address | int64 }}
    targetPort: {{ trimPrefix ":" $value.service_address | int64 }}
    protocol: "UDP"
    name: "udp_listener"
    {{- end }}
    {{- if eq $key "webhooks" }}
  - port: {{ trimPrefix ":" $value.service_address | int64 }}
    targetPort: {{ trimPrefix ":" $value.service_address | int64 }}
    name: "webhooks"
    {{- end }}
  {{- end -}}
  {{- end }}
  {{- range $objectKey, $objectValue := .Values.config.outputs }}
  {{- range $key, $value := . -}}
    {{- $tp := typeOf $value -}}
    {{- if eq $key "prometheus_client" }}
  - port: {{ trimPrefix ":" $value.listen | int64 }}
    targetPort: {{ trimPrefix ":" $value.listen | int64 }}
    name: "prometheus-client"
    {{- end }}
  {{- end -}}
  {{- end }}
  selector:
    app.kubernetes.io/name: {{ include "telegraf.name" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
{{- end -}}
