{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ include "iceberg-catalog.serviceAccountName" . }}
  labels:
    {{- include "iceberg-catalog.labels" . | nindent 4 }}
    app.kubernetes.io/component: rbac
  {{- with .Values.serviceAccount.annotations }}
  annotations:
    {{- toYaml . | nindent 4 }}
  {{- end }}
automountServiceAccountToken: {{ .Values.serviceAccount.automount }}
---
# Get jobs to detect if migrations finished
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: {{ include "iceberg-catalog.fullname" . }}
  labels:
    {{- include "iceberg-catalog.labels" . | nindent 4 }}
    app.kubernetes.io/component: rbac
rules:
- apiGroups:
  - batch
  resources:
  - jobs
  verbs:
  - get
  - list
  - watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: {{ include "iceberg-catalog.fullname" . }}-rolebinding
  labels:
    {{- include "iceberg-catalog.labels" . | nindent 4 }}
    app.kubernetes.io/component: rbac
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: {{ include "iceberg-catalog.fullname" . }}
subjects:
- kind: ServiceAccount
  name: {{ include "iceberg-catalog.serviceAccountName" . }}
  namespace: {{ .Release.Namespace }}

{{- if .Values.auth.k8s.enabled }}
{{- if .Values.auth.k8s.createClusterRoleBinding }}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: {{ .Release.Namespace }}:{{ include "iceberg-catalog.fullname" . }}-token-review
  labels:
    {{- include "iceberg-catalog.labels" . | nindent 4 }}
    app.kubernetes.io/component: rbac
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:auth-delegator
subjects:
- kind: ServiceAccount
  name: {{ include "iceberg-catalog.serviceAccountName" . }}
  namespace: {{ .Release.Namespace }}
{{- end }}
{{- end }}
{{- end }}
