{{- if .Values.networkPolicy.enabled }}
kind: NetworkPolicy
apiVersion: {{ .Values.networkPolicy.apiVersion }}
metadata:
  name: "{{ .Release.Name }}-{{ .Values.controller.componentName }}"
  namespace: {{ template "jenkins.namespace" . }}
  labels:
    "app.kubernetes.io/name": '{{ template "jenkins.name" .}}'
    {{- if .Values.renderHelmLabels }}
    "helm.sh/chart": "{{ template "jenkins.label" .}}"
    {{- end }}
    "app.kubernetes.io/managed-by": "{{ .Release.Service }}"
    "app.kubernetes.io/instance": "{{ .Release.Name }}"
    "app.kubernetes.io/component": "{{ .Values.controller.componentName }}"
spec:
  podSelector:
    matchLabels:
      "app.kubernetes.io/component": "{{ .Values.controller.componentName }}"
      "app.kubernetes.io/instance": "{{ .Release.Name }}"
  ingress:
    # Allow web access to the UI
    - ports:
      - port: {{ .Values.controller.targetPort }}
    {{- if .Values.controller.agentListenerEnabled }}
    # Allow inbound connections from agents
    - from:
      {{- if .Values.networkPolicy.internalAgents.allowed }}
      - podSelector:
          matchLabels:
            "jenkins/{{ .Release.Name }}-{{ .Values.agent.componentName }}": "true"
            {{- range $k,$v:= .Values.networkPolicy.internalAgents.podLabels }}
            {{ $k }}: {{ $v }}
            {{- end }}
        {{- if .Values.networkPolicy.internalAgents.namespaceLabels }}
        namespaceSelector:
          matchLabels:
            {{- range $k,$v:= .Values.networkPolicy.internalAgents.namespaceLabels }}
            {{ $k }}: {{ $v }}
            {{- end }}
        {{- end }}
      {{- end }}
      {{- if or .Values.networkPolicy.externalAgents.ipCIDR .Values.networkPolicy.externalAgents.except }}
      - ipBlock:
          cidr: {{ required "ipCIDR is required if you wish to allow external agents to connect to Jenkins Controller." .Values.networkPolicy.externalAgents.ipCIDR }}
          {{- if .Values.networkPolicy.externalAgents.except }}
          except:
          {{- range .Values.networkPolicy.externalAgents.except }}
          - {{ . }}
          {{- end }}
          {{- end }}
      {{- end }}
      ports:
      - port: {{ .Values.controller.agentListenerPort }}
    {{- end }}
{{- if .Values.agent.enabled }}
---
kind: NetworkPolicy
apiVersion: {{ .Values.networkPolicy.apiVersion }}
metadata:
  name: "{{ .Release.Name }}-{{ .Values.agent.componentName }}"
  namespace: {{ template "jenkins.namespace" . }}
  labels:
    "app.kubernetes.io/name": '{{ template "jenkins.name" .}}'
    {{- if .Values.renderHelmLabels }}
    "helm.sh/chart": "{{ template "jenkins.label" .}}"
    {{- end }}
    "app.kubernetes.io/managed-by": "{{ .Release.Service }}"
    "app.kubernetes.io/instance": "{{ .Release.Name }}"
    "app.kubernetes.io/component": "{{ .Values.controller.componentName }}"
spec:
  podSelector:
    matchLabels:
      # DefaultDeny
      "jenkins/{{ .Release.Name }}-{{ .Values.agent.componentName }}": "true"
{{- end }}
{{- end }}
