{{- if .Values.serviceAccount.create }}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ include "emqx.serviceAccountName" . }}
  namespace: {{ .Release.Namespace }}
  labels:
    app.kubernetes.io/name: {{ include "emqx.name" . }}
    helm.sh/chart: {{ include "emqx.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  {{- with .Values.serviceAccount.annotations }}
  annotations:
    {{- toYaml . | nindent 4 }}
  {{- end }}
{{- end }}

---
{{- if .Values.serviceAccount.create }}
{{- if eq .Values.emqxConfig.EMQX_CLUSTER__DISCOVERY_STRATEGY "k8s" }}
kind: Role
{{- if semverCompare ">=1.17-0" .Capabilities.KubeVersion.GitVersion }}
apiVersion: rbac.authorization.k8s.io/v1
{{- else }}
apiVersion: rbac.authorization.k8s.io/v1beta1
{{- end }}
metadata:
  namespace: {{ .Release.Namespace }}
  name: {{ include "emqx.fullname" . }}
rules:
- apiGroups:
  - ""
  resources:
  - endpoints
  verbs:
  - get
  - watch
  - list
{{- end }}
{{- end }}

---
{{- if .Values.serviceAccount.create }}
{{- if eq .Values.emqxConfig.EMQX_CLUSTER__DISCOVERY_STRATEGY "k8s" }}
kind: RoleBinding
{{- if semverCompare ">=1.17-0" .Capabilities.KubeVersion.GitVersion }}
apiVersion: rbac.authorization.k8s.io/v1
{{- else }}
apiVersion: rbac.authorization.k8s.io/v1beta1
{{- end }}
metadata:
  namespace: {{ .Release.Namespace }}
  name: {{ include "emqx.fullname" . }}
subjects:
  - kind: ServiceAccount
    name: {{ include "emqx.serviceAccountName" . }}
    namespace: {{ .Release.Namespace }}
roleRef:
  kind: Role
  name: {{ include "emqx.fullname" . }}
  apiGroup: rbac.authorization.k8s.io
{{- end }}
{{- end }}
