---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: job-cleanup-sa
  namespace: flux-builds
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: job-cleanup-role
  namespace: flux-builds
rules:
- apiGroups: ["batch"]
  resources: ["jobs"]
  verbs: ["list", "delete", "deletecollection"]
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["list", "delete"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: job-cleanup-binding
  namespace: flux-builds
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: job-cleanup-role
subjects:
- kind: ServiceAccount
  name: job-cleanup-sa
  namespace: flux-builds
---
apiVersion: batch/v1
kind: CronJob
metadata:
  name: cleanup-old-build-jobs
  namespace: flux-builds
spec:
  schedule: "*/30 * * * *"  # Run every 30 minutes
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 1
  failedJobsHistoryLimit: 1
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: job-cleanup-sa
          restartPolicy: Never
          containers:
          - name: cleanup
            image: bitnami/kubectl:latest
            command:
            - /bin/bash
            - -c
            - |
              set -e
              echo "===== Cleaning up old build jobs ====="
              date

              # Keep only the last 10 successful jobs
              echo "Finding old successful jobs..."
              SUCCESSFUL_JOBS=$(kubectl get jobs -n flux-builds \
                -l app=neonvortex \
                --sort-by=.metadata.creationTimestamp \
                --field-selector status.successful=1 \
                -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' | head -n -10)

              if [ -n "$SUCCESSFUL_JOBS" ]; then
                echo "Deleting old successful jobs:"
                echo "$SUCCESSFUL_JOBS"
                echo "$SUCCESSFUL_JOBS" | xargs -r kubectl delete job -n flux-builds
              else
                echo "No old successful jobs to delete"
              fi

              # Delete failed jobs older than 1 hour
              echo ""
              echo "Finding old failed jobs..."
              CUTOFF_TIME=$(date -u -d '1 hour ago' '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null || date -u -v-1H '+%Y-%m-%dT%H:%M:%SZ')

              FAILED_JOBS=$(kubectl get jobs -n flux-builds \
                -l app=neonvortex \
                --field-selector status.successful=0 \
                -o json | \
                jq -r --arg cutoff "$CUTOFF_TIME" \
                '.items[] | select(.status.completionTime < $cutoff or .status.startTime < $cutoff) | .metadata.name')

              if [ -n "$FAILED_JOBS" ]; then
                echo "Deleting old failed jobs:"
                echo "$FAILED_JOBS"
                echo "$FAILED_JOBS" | xargs -r kubectl delete job -n flux-builds
              else
                echo "No old failed jobs to delete"
              fi

              # Delete jobs older than 24 hours regardless of status
              echo ""
              echo "Finding jobs older than 24 hours..."
              CUTOFF_24H=$(date -u -d '24 hours ago' '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null || date -u -v-24H '+%Y-%m-%dT%H:%M:%SZ')

              OLD_JOBS=$(kubectl get jobs -n flux-builds \
                -l app=neonvortex \
                -o json | \
                jq -r --arg cutoff "$CUTOFF_24H" \
                '.items[] | select(.metadata.creationTimestamp < $cutoff) | .metadata.name')

              if [ -n "$OLD_JOBS" ]; then
                echo "Deleting jobs older than 24 hours:"
                echo "$OLD_JOBS"
                echo "$OLD_JOBS" | xargs -r kubectl delete job -n flux-builds
              else
                echo "No jobs older than 24 hours"
              fi

              echo ""
              echo "===== Cleanup complete ====="
              kubectl get jobs -n flux-builds -l app=neonvortex
