apiVersion: v1
kind: Namespace
metadata:
  name: quotad
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: quotad-script
  namespace: quotad
data:
  quotad.sh: |
    #!/usr/bin/env bash
    set -eou pipefail

    echo "-----------------------------------------"
    echo "quotad script written by Aaron 17.09.2023"
    echo "-----------------------------------------"
    while read ns; do
        ns=$(echo $ns | cut -d "/" -f 2)
        echo -n "check if $ns has the unlimited label"
        if [[ $(kubectl get ns $ns -o json | jq -r '.metadata.labels["yolokube.de/unlimited-quota"]') == "true" ]]; then
            echo ": yes"
            # remove the quota elements if they exist
            kubectl delete -n $ns -f /quotad-script/default-quota.yaml --ignore-not-found=true
        else
            echo ": no"
            # set the quota elements  if they do not already exist
            kubectl apply -n $ns -f /quotad-script/default-quota.yaml
        fi
        echo "-----------------------------------------"
    done <<< $(kubectl get ns -o name)
  default-quota.yaml: |
    ---
    apiVersion: v1
    kind: ResourceQuota
    metadata:
      name: pvc-quota
    spec:
      hard:
        persistentvolumeclaims.storageclass.storage.k8s.io/longhorn: 50Gi
    ---
    apiVersion: v1
    kind: LimitRange
    metadata:
      name: storagelimits
    spec:
      limits:
      - type: PersistentVolumeClaim
        max:
          storage: 10Gi
---
apiVersion: batch/v1
kind: CronJob
metadata:
  name: quotad
  namespace: quotad
spec:
  schedule: "*/2 * * * *"
  successfulJobsHistoryLimit: 1
  failedJobsHistoryLimit: 3
  jobTemplate:
    spec:
      ttlSecondsAfterFinished: 240
      template:
        spec:
          volumes:
            - name: quotad-script
              configMap:
                name: quotad-script
                defaultMode: 0777
          containers:
            - name: quotad
              image: bitnami/kubectl
              env:
                - name: NODE_NAME
                  valueFrom:
                    fieldRef:
                      fieldPath: spec.nodeName
              command: ["/bin/sh", "-c", "/quotad-script/quotad.sh"]
              imagePullPolicy: IfNotPresent
              volumeMounts:
                - mountPath: /quotad-script
                  name: quotad-script
          restartPolicy: Never
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: quotad-role
  namespace: quotad
rules:
  - apiGroups: [""]
    resources: ["namespaces"]
    verbs: ["get", "patch", "list"]
  - apiGroups: [""]
    resources: ["resourcequotas", "limitranges"]
    verbs: ["get", "patch", "list", "create", "delete", "update"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: quotad-binding
  namespace: quotad
subjects:
  - kind: ServiceAccount
    name: default
    namespace: quotad
roleRef:
  kind: ClusterRole
  name: quotad-role
  apiGroup: rbac.authorization.k8s.io