apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: osd-delete-backplane-serviceaccounts
  namespace: openshift-backplane
spec:
  failedJobsHistoryLimit: 5
  successfulJobsHistoryLimit: 3
  concurrencyPolicy: Replace
  schedule: "*/10 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          affinity:
            nodeAffinity:
              preferredDuringSchedulingIgnoredDuringExecution:
              - preference:
                  matchExpressions:
                  - key: node-role.kubernetes.io/infra
                    operator: Exists
                weight: 1
          tolerations:
            - effect: NoSchedule
              key: node-role.kubernetes.io/infra
              operator: Exists
          restartPolicy: Never
          serviceAccountName: osd-delete-backplane-serviceaccounts
          containers:
            - name: osd-delete-backplane-serviceaccounts
              imagePullPolicy: Always
              image: image-registry.openshift-image-registry.svc:5000/openshift/cli:latest
              args:
                - /bin/bash
                - -c
                - |
                  for ns in $(oc get ns --no-headers | grep -e ^openshift-backplane-.* | awk '{print $1}');do
                      for sa in $(oc get sa -n $ns -l managed.openshift.io/backplane=true --no-headers | awk '{print $1}');do
                        creation=$(date -d $(oc get sa $sa -n $ns -o jsonpath='{.metadata.creationTimestamp}') '+%s');
                        now=$(date +%s);
                        expiryMins=$(oc get sa $sa -n $ns -o jsonpath='{.metadata.annotations.managed\.openshift\.io/backplane-expiry-duration}');
                        if [[ $(expr $((now-creation)) \> ${expiryMins:=720} \* 60) == 1 ]]; then
                          oc delete sa $sa -n $ns
                        fi
                      done;
                  done;