{{- 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 }}
    {{- if .Values.commonLabels }}
    {{- include "sealed-secrets.render" (dict "value" .Values.commonLabels "context" $) | nindent 4 }}
    {{- end }}
  annotations:
    {{- if .Values.commonAnnotations }}
    {{- include "sealed-secrets.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
    {{- end }}
spec:
  podSelector:
    matchLabels: {{- include "sealed-secrets.matchLabels" . | nindent 6 }}
  ingress:
    - ports:
      - port: {{ .Values.service.port }}
      - port: {{ .Values.metrics.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 }}
