{{- if .Values.worker.networkPolicy.enabled }}
kind: NetworkPolicy
apiVersion: {{ include "common.capabilities.networkPolicy.apiVersion" . }}
metadata:
  name: {{ template "shuffle.worker.name" . }}
  namespace: {{ include "common.names.namespace" . | quote }}
  labels: {{- include "shuffle.worker.labels" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 4 }}
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
spec:
  podSelector:
    matchLabels: {{- include "shuffle.worker.matchLabels" . | nindent 6 }}
  policyTypes:
    - Ingress
    - Egress
  egress:
    {{- if .Values.worker.networkPolicy.allowExternalEgress }}
    - {}
    {{- else }}
    # Allow DNS resolution with an in-cluster DNS server
    - ports:
        - port: 53
          protocol: UDP
        - port: 53
          protocol: TCP
      to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: kube-system
    # Allow arbitrary connections to apps. Apps will typically use port 80/TCP, but this is not enforced.
    - to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: {{ .Release.Namespace }}
          podSelector:
            matchLabels: {{- include "shuffle.app.matchLabels" . | nindent 14 }}
    {{- if .Values.worker.networkPolicy.extraEgress }}
    {{- include "common.tplvalues.render" ( dict "value" .Values.worker.networkPolicy.extraEgress "context" $ ) | nindent 4 }}
    {{- end }}
    {{- end }}
  ingress:
    - ports:
        - port: 33333
          protocol: TCP
      {{- if not .Values.worker.networkPolicy.allowExternal }}
      from:
        # Allow traffic from orborus
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: {{ .Release.Namespace }}
          podSelector:
            matchLabels: {{ include "shuffle.orborus.matchLabels" . | nindent 14 }}
        # Allow traffic from apps
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: {{ .Release.Namespace }}
          podSelector:
            matchLabels: {{- include "shuffle.app.matchLabels" . | nindent 14 }}
      {{- end }}
    {{- if .Values.worker.networkPolicy.extraIngress }}
    {{- include "common.tplvalues.render" ( dict "value" .Values.worker.networkPolicy.extraIngress "context" $ ) | nindent 4 }}
    {{- end }}
{{- end }}
