---
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: sre-build-test
  namespace: openshift-build-test
spec:
  failedJobsHistoryLimit: 5
  successfulJobsHistoryLimit: 3
  concurrencyPolicy: Forbid
  schedule: "11 * * * *"
  jobTemplate:
    spec:
      activeDeadlineSeconds: 900
      template:
        spec:
          affinity:
            nodeAffinity:
              requiredDuringSchedulingIgnoredDuringExecution:
                nodeSelectorTerms:
                - matchExpressions:
                  - key: "node-role.kubernetes.io/infra"
                    operator: Exists
          tolerations:
          - operator: Exists
            key: node-role.kubernetes.io/infra
            effect: NoSchedule
          serviceAccountName: sre-build-test
          restartPolicy: Never
          containers:
          - name: sre-build-test
            image: image-registry.openshift-image-registry.svc:5000/openshift/cli:latest
            imagePullPolicy: Always
            env:
              - name: POD_NAME
                valueFrom:
                  fieldRef:
                    fieldPath: metadata.name
              - name: POD_NS
                valueFrom:
                  fieldRef:
                    fieldPath: metadata.namespace
            command:
            - /bin/bash
            - -c
            - |
              # ensure we fail if something exits non-zero
              set -o errexit
              set -o nounset

              # set NS to include job name, to ease linking namespace to a specific job
              JOB_PREFIX=sre-build-test
              NS="${POD_NS}-${POD_NAME##${JOB_PREFIX}-}"
              JOB_NAME=$(echo "${POD_NAME}" | rev | cut -d- -f2- | rev)

              # cleanup traps on exiting, so these always run
              cleanup () {
                echo "$(date): Done, deleting build NS=$NS"
                oc delete ns "${NS}" --wait=false
              }
              trap "cleanup" EXIT SIGINT

              # create ns
              oc create -f - <<EOF
              apiVersion: v1
              kind: Namespace
              metadata:
                name: "${NS}"
                managed.openshift.io/sre-build-test: "${JOB_NAME}"
              EOF

              # wait for sa to be created
              until oc -n "${NS}" get sa default >/dev/null; do
                echo "$(date): Waiting for service account to be created"
                sleep 5
              done

              # run build
              oc -n "${NS}" new-build --name="${JOB_PREFIX}" --binary --strategy source --docker-image registry.redhat.io/ubi8/go-toolset:latest
              cat <<EOF > /tmp/main.go
              package main
              import (
                     "fmt"
              )

              func main() {
                      fmt.Println("Hello Openshift SRE :)")
              }
              EOF

              while ! oc -n "${NS}" start-build "${JOB_PREFIX}" --from-file=/tmp/main.go
              do
                echo "Failed to start build, retrying in 15 seconds."
                sleep 15s
              done

              echo "$(date): Waiting for build to complete."
              while :
              do
                ST=$(oc -n "${NS}" get build -o custom-columns=STATUS:.status.phase --no-headers)
                case ${ST} in
                  "")
                    # if build status is blank, assume we are still starting the build
                    ST="Starting"
                    ;;
                  Failed)
                    echo "$(date): Build Failed" >&2
                    oc logs -n "${NS}" -c build "${JOB_PREFIX}"
                    exit 1
                    ;;
                  Cancelled)
                    echo "$(date): Build was Cancelled" >&2
                    oc logs -n "${NS}" -c build "${JOB_PREFIX}"
                    exit 1
                    ;;
                  Complete)
                    echo "$(date): Build Complete"
                    oc get jobs -n "$POD_NS" --sort-by=.status.startTime -o custom-columns=":metadata.name" --no-headers | head -n -1 | xargs oc -n "$POD_NS" delete job --ignore-not-found --wait=false

                    # clean up any old namespaces, other than the current one
                    echo "$(date): Cleaning up old namespaces"
                    oc delete ns -l "managed.openshift.io/sre-build-test,kubernetes.io/metadata.name!=${NS}" --ignore-not-found --wait=false
                    break
                    ;;
                esac
                echo "$(date): Build is ${ST}; checking build again in 15 seconds, NS=${NS}"
                sleep 15
              done
              exit 0
