{{- /*
Copyright Broadcom, Inc. All Rights Reserved.
SPDX-License-Identifier: APACHE-2.0
*/}}

# Based on upstream configuration: https://github.com/prometheus-operator/kube-prometheus/commit/968cb8fd22a1e21e63e8702bc1c0a0a4547e6d15
{{- if and .Values.alertmanager.enabled .Values.alertmanager.networkPolicy.enabled }}
kind: NetworkPolicy
apiVersion: {{ include "common.capabilities.networkPolicy.apiVersion" . }}
metadata:
  name: {{ template "kube-prometheus.alertmanager.fullname" . }}
  namespace: {{ include "common.names.namespace" . | quote }}
  labels: {{- include "kube-prometheus.alertmanager.labels" . | nindent 4 }}
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
spec:
  podSelector:
    matchLabels: {{- include "kube-prometheus.alertmanager.matchLabels" . | nindent 6 }}
  policyTypes:
    - Ingress
    - Egress
  {{- if .Values.alertmanager.networkPolicy.allowExternalEgress }}
  egress:
    - {}
  {{- else }}
  egress:
    {{- if .Values.alertmanager.networkPolicy.extraEgress }}
    {{- include "common.tplvalues.render" ( dict "value" .Values.alertmanager.networkPolicy.extraEgress "context" $ ) | nindent 4 }}
    {{- end }}
  {{- end }}
  ingress:
    {{/* The deployed AlertManager objects have the ports hardcoded
       https://github.com/prometheus-operator/prometheus-operator/blob/bdfc5ec0055471b2f626e63682ee7decd0c41db9/pkg/alertmanager/statefulset.go#L252 */}}
    - ports:
        - port: 8080
        - port: 9093
        - port: 9094
      {{- if not .Values.alertmanager.networkPolicy.allowExternal }}
      from:
        - podSelector:
            matchLabels:
              {{ template "common.names.fullname" . }}-client: "true"
        - podSelector:
            matchLabels: {{- include "common.labels.matchLabels" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 14 }}
        {{- if .Values.alertmanager.networkPolicy.ingressNSMatchLabels }}
        - namespaceSelector:
            matchLabels:
              {{- range $key, $value := .Values.alertmanager.networkPolicy.ingressNSMatchLabels }}
              {{ $key | quote }}: {{ $value | quote }}
              {{- end }}
          {{- if .Values.alertmanager.networkPolicy.ingressNSPodMatchLabels }}
          podSelector:
            matchLabels:
              {{- range $key, $value := .Values.alertmanager.networkPolicy.ingressNSPodMatchLabels }}
              {{ $key | quote }}: {{ $value | quote }}
              {{- end }}
          {{- end }}
        {{- end }}
      {{- end }}
    {{- if .Values.alertmanager.networkPolicy.extraIngress }}
    {{- include "common.tplvalues.render" ( dict "value" .Values.alertmanager.networkPolicy.extraIngress "context" $ ) | nindent 4 }}
    {{- end }}
{{- end }}
