{{- $app := .Values.vmagent }}
{{- $rbac := $app.rbac }}
{{- if and $app.enabled (not (empty $rbac.rules)) -}}
{{- $ctx := dict "helm" . "appKey" "vmagent" }}
{{- $fullname := include "vm.managed.fullname" $ctx }}
{{- $ns := include "vm.namespace" $ctx }}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: {{ ternary "RoleBinding" "ClusterRoleBinding" $rbac.namespaced }}
metadata:
  name: {{ $fullname }}
  {{- if $rbac.namespaced }}
  namespace: {{ $ns }}
  {{- end }}
  {{- $_ := set $ctx "extraLabels" $rbac.extraLabels }}
  labels: {{ include "vm.labels" $ctx | nindent 4 }}
  {{- $_ := unset $ctx "extraLabels" }}
  {{- with $rbac.annotations }}
  annotations: {{ toYaml . | nindent 4 }}
  {{- end }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: {{ ternary "Role" "ClusterRole" $rbac.namespaced }}
  name: {{ $fullname }}
subjects:
  - kind: ServiceAccount
    name: {{ $fullname }}
    namespace: {{ $ns }}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: {{ ternary "Role" "ClusterRole" $rbac.namespaced }}
metadata:
  name: {{ $fullname }}
  {{- if $rbac.namespaced }}
  namespace: {{ include "vm.namespace" $ctx }}
  {{- end }}
  {{- $_ := set $ctx "extraLabels" $rbac.extraLabels }}
  labels: {{ include "vm.labels" $ctx | nindent 4 }}
  {{- $_ := unset $ctx "extraLabels" }}
  {{- with $rbac.annotations }}
  annotations: {{ toYaml . | nindent 4 }}
  {{- end }}
rules: {{ tpl (toYaml $rbac.rules) . | nindent 2 }}
{{- end }}
