---
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: airm-quota-enforcement-for-workloads
spec:
  background: false
  rules:
    - match:
        resources:
          kinds:
            - Deployment
            - StatefulSet
            - Pod
          namespaceSelector:
            matchExpressions:
              - key: airm.silogen.ai/project-id
                operator: Exists
      mutate:
        patchStrategicMerge:
          metadata:
            labels:
              kueue.x-k8s.io/queue-name: '{{request.namespace }}'
      name: set-queue-name-from-namespace-default
      preconditions:
        all:
          - key: '{{request.object.metadata.labels."kueue.x-k8s.io/queue-name" || '''' }}'
            operator: NotEquals
            value: '{{request.namespace }}'
    - match:
        resources:
          kinds:
            - Job
          namespaceSelector:
            matchExpressions:
              - key: airm.silogen.ai/project-id
                operator: Exists
      mutate:
        patchStrategicMerge:
          metadata:
            labels:
              kueue.x-k8s.io/queue-name: '{{request.namespace }}'
          spec:
            suspend: true
      name: set-queue-name-from-namespace-jobs
      preconditions:
        all:
          - key: '{{request.object.metadata.labels."kueue.x-k8s.io/queue-name" || '''' }}'
            operator: NotEquals
            value: '{{request.namespace }}'
    - match:
        resources:
          kinds:
            - CronJob
          namespaceSelector:
            matchExpressions:
              - key: airm.silogen.ai/project-id
                operator: Exists
      mutate:
        patchStrategicMerge:
          spec:
            jobTemplate:
              metadata:
                labels:
                  kueue.x-k8s.io/queue-name: '{{request.namespace }}'
              spec:
                suspend: true
      name: set-queue-name-from-namespace-cronjobs
      preconditions:
        all:
          - key: '{{request.object.spec.jobTemplate.metadata.labels."kueue.x-k8s.io/queue-name" || '''' }}'
            operator: NotEquals
            value: '{{request.namespace }}'
    - match:
        resources:
          kinds:
            - KaiwoJob
            - KaiwoService
          namespaceSelector:
            matchExpressions:
              - key: airm.silogen.ai/project-id
                operator: Exists
      mutate:
        patchStrategicMerge:
          spec:
            clusterQueue: '{{request.namespace }}'
      name: set-queue-name-from-namespace-kaiwo
      preconditions:
        all:
          - key: '{{request.object.spec.clusterQueue || '''' }}'
            operator: NotEquals
            value: '{{request.namespace }}'
