---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: cleaner
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: cleaner
rules:
  - apiGroups: ["tekton.dev"]
    resources: ["pipelineruns"]
    verbs: ["delete", "get", "watch", "list"]
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: cleaner-to-cleaner
roleRef:
  kind: Role
  name: cleaner
  apiGroup: rbac.authorization.k8s.io
subjects:
  - kind: ServiceAccount
    name: cleaner
---
apiVersion: batch/v1
kind: CronJob
metadata:
  name: cleanup-pipelineruns
spec:
  schedule: "*/15 * * * *"
  concurrencyPolicy: Forbid
  jobTemplate:
    spec:
      template:
        spec:
          restartPolicy: OnFailure
          serviceAccount: cleaner
          containers:
            - name: kubectl
              image: bitnami/kubectl:latest
              env:
                - name: NUM_TO_KEEP
                  value: "1"
              command:
                - /bin/bash
                - -c
                - |
                    TO_DELETE="$(kubectl get pipelinerun -o jsonpath='{range .items[?(@.status.completionTime)]}{.status.completionTime}{" "}{.metadata.name}{"\n"}{end}' | sort | head -n -${NUM_TO_KEEP} | awk '{ print $2}')"
                    test -n "$TO_DELETE" && kubectl delete pipelinerun ${TO_DELETE} || true
