{{- $ingressNamespaces := default (include "traefik.namespace" . | list) .Values.providers.kubernetesIngress.namespaces -}}
{{- $CRDNamespaces := default (include "traefik.namespace" . | list) .Values.providers.kubernetesCRD.namespaces -}}
{{- $allNamespaces := uniq (concat $ingressNamespaces $CRDNamespaces) -}}

{{- if and .Values.rbac.enabled .Values.rbac.namespaced -}}
{{- range $allNamespaces }}
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: {{ template "traefik.fullname" $ }}
  namespace: {{ . }}
  labels:
    {{- include "traefik.labels" $ | nindent 4 }}
rules:
  - apiGroups:
      - ""
    resources:
      - services
      - endpoints
      - secrets
    verbs:
      - get
      - list
      - watch
{{- if (and (has . $ingressNamespaces) $.Values.providers.kubernetesIngress.enabled) }}
  - apiGroups:
      - extensions
      - networking.k8s.io
    resources:
      - ingresses
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - extensions
      - networking.k8s.io
    resources:
      - ingresses/status
    verbs:
      - update
{{- end -}}
{{- if (and (has . $CRDNamespaces) $.Values.providers.kubernetesCRD.enabled) }}
  - apiGroups:
      - traefik.io
      {{- if semverCompare "<3.0.0-0" (include "imageVersion" $) }}
      - traefik.containo.us
      {{- end }}
    resources:
      - ingressroutes
      - ingressroutetcps
      - ingressrouteudps
      - middlewares
      - middlewaretcps
      - tlsoptions
      - tlsstores
      - traefikservices
      - serverstransports
      {{- if semverCompare ">=3.0.0-0" (include "imageVersion" $) }}
      - serverstransporttcps
      {{- end }}
    verbs:
      - get
      - list
      - watch
{{- end -}}
{{- if $.Values.podSecurityPolicy.enabled }}
  - apiGroups:
      - extensions
    resourceNames:
      - {{ template "traefik.fullname" $ }}
    resources:
      - podsecuritypolicies
    verbs:
      - use
{{- end -}}
{{- end -}}
{{- end -}}
