# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

{{- if .Values.rbac.create }}
{{- if .Values.rbac.namespaceRestricted }}
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: {{ include "snapshot.fullname" . }}-agent
  namespace: {{ .Release.Namespace }}
  labels:
    {{- include "snapshot.labels" . | nindent 4 }}
rules:
  # Watch and annotate pods in this namespace to drive checkpoint/restore lifecycle
  - apiGroups: [""]
    resources: ["pods"]
    verbs: ["get", "list", "watch", "patch", "update"]
  # Patch checkpoint Jobs with terminal checkpoint status
  - apiGroups: ["batch"]
    resources: ["jobs"]
    verbs: ["get", "patch", "update"]
  # Coordinate checkpoint ownership with per-Job leases
  - apiGroups: ["coordination.k8s.io"]
    resources: ["leases"]
    verbs: ["get", "create", "update", "delete"]
  # Emit operational events on pod/restore lifecycle updates
  - apiGroups: [""]
    resources: ["events"]
    verbs: ["create"]
  # Resolve DRA GPU UUIDs via ResourceClaim allocation (namespace-scoped)
  - apiGroups: ["resource.k8s.io"]
    resources: ["resourceclaims"]
    verbs: ["get", "list"]
{{- else }}
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: {{ include "snapshot.fullname" . }}-agent
  labels:
    {{- include "snapshot.labels" . | nindent 4 }}
rules:
  # Watch and annotate pods cluster-wide on assigned nodes
  - apiGroups: [""]
    resources: ["pods"]
    verbs: ["get", "list", "watch", "patch", "update"]
  # Patch checkpoint Jobs with terminal checkpoint status
  - apiGroups: ["batch"]
    resources: ["jobs"]
    verbs: ["get", "patch", "update"]
  # Coordinate checkpoint ownership with per-Job leases
  - apiGroups: ["coordination.k8s.io"]
    resources: ["leases"]
    verbs: ["get", "create", "update", "delete"]
  # Emit operational events on pod/restore lifecycle updates
  - apiGroups: [""]
    resources: ["events"]
    verbs: ["create"]
  # Resolve DRA GPU UUIDs via ResourceClaim and ResourceSlice
  - apiGroups: ["resource.k8s.io"]
    resources: ["resourceclaims", "resourceslices"]
    verbs: ["get", "list"]
{{- end }}
{{- end }}

{{- if and .Values.rbac.create .Values.rbac.namespaceRestricted }}
---
# ResourceSlices are cluster-scoped; agent needs this when using a namespace-restricted Role
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: {{ include "snapshot.fullname" . }}-agent-resourceslices
  labels:
    {{- include "snapshot.labels" . | nindent 4 }}
rules:
  - apiGroups: ["resource.k8s.io"]
    resources: ["resourceslices"]
    verbs: ["get", "list"]
{{- end }}
