{{- if and .Values.rbac.create (not .Values.rbac.namespaced) .Values.server.scrape.enabled }}
{{- $ctx := dict "helm" . "appKey" "server" }}
{{- $fullname := include "vm.plain.fullname" $ctx }}
{{- $ns := include "vm.namespace" $ctx }}
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: {{ $fullname }}
  {{- $_ := set $ctx "extraLabels" .Values.rbac.extraLabels }}
  labels: {{ include "vm.metaLabels" $ctx | nindent 4 }}
  {{- $_ := unset $ctx "extraLabels" }}
  {{- with .Values.rbac.annotations }}
  annotations: {{ toYaml . | nindent 4 }}
  {{- end }}
rules:
  - apiGroups:
    - discovery.k8s.io
    resources:
    - endpointslices
    verbs: ["get", "list", "watch"]
  - apiGroups: [""]
    resources:
      - nodes
      - nodes/metrics
      - services
      - endpoints
      - pods
    verbs: ["get", "list", "watch"]
  - apiGroups:
      - networking.k8s.io
    resources:
      - ingresses
    verbs: ["get", "list", "watch"]
  - nonResourceURLs: ["/metrics"]
    verbs: ["get"]
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: {{ $fullname }}
  {{- $_ := set $ctx "extraLabels" .Values.rbac.extraLabels }}
  labels: {{ include "vm.metaLabels" $ctx | nindent 4 }}
  {{- $_ := unset $ctx "extraLabels" }}
  {{- with .Values.rbac.annotations }}
  annotations: {{ toYaml . | nindent 4 }}
  {{- end }}
subjects:
  - kind: ServiceAccount
    name: {{ .Values.serviceAccount.name | default $fullname }}
    namespace: {{ $ns }}
roleRef:
  kind: ClusterRole
  name: {{ $fullname }}
  apiGroup: rbac.authorization.k8s.io
{{- end -}}
