{{- if .Values.networkPolicy.enabled }}
apiVersion: {{ include "sealed-secrets.networkPolicy.apiVersion" . }}
kind: NetworkPolicy
metadata:
  name: {{ include "sealed-secrets.fullname" . }}
  namespace: {{ include "sealed-secrets.namespace" . }}
  labels: {{- include "sealed-secrets.labels" . | nindent 4 }}
spec:
  podSelector:
    matchLabels: {{- include "sealed-secrets.matchLabels" . | nindent 6 }}
  ingress:
    - ports:
      - port: {{ .Values.service.port }}
  {{- if .Values.networkPolicy.egress.enabled }}
  egress:
    - to:
      {{- if not .Values.networkPolicy.egress.kubeapiCidr }}
      {{- $kubernetesEndpoint := lookup "v1" "Endpoints" "default" "kubernetes" }}
      {{- if $kubernetesEndpoint }}
        {{- range $kubernetesAddress := (first $kubernetesEndpoint.subsets).addresses }}
      - ipBlock:
          cidr: {{ $kubernetesAddress.ip }}/32
        {{- end}}      
      ports:
        {{- range $kubernetesPort := (first $kubernetesEndpoint.subsets).ports }}
        - protocol: {{ $kubernetesPort.protocol }}
          port: {{ $kubernetesPort.port }}
        {{- end }}
      {{- end}}
      {{- else }}
      - ipBlock:
          cidr: {{ .Values.networkPolicy.egress.kubeapiCidr }}
      ports:
        - protocol: TCP
          port: {{ .Values.networkPolicy.egress.kubeapiPort }}
      {{- end }}
  {{- end }}
{{- end }}
