# Copyright 2021 The Selkies Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

kind: CronJob
apiVersion: batch/v1beta1
metadata:
  name: update-image-cache
  labels:
    k8s-app: update-image-cache
spec:
  # UTC time,
  schedule: ${_IMAGE_BUILD_SCHEDULE}
  startingDeadlineSeconds: 7200
  concurrencyPolicy: Replace
  successfulJobsHistoryLimit: 1
  jobTemplate:
    spec:
      activeDeadlineSeconds: 7200
      template:
        spec:
          serviceAccount: pod-broker
          restartPolicy: OnFailure

          volumes:
            ###
            # Cloudbuild contents
            ###
            - name: cloudbuild
              configMap:
                name: image-cache-update-cloudbuild
          containers:
            ###
            # per-project node cache updater job.
            ###
            - image: gcr.io/${PROJECT_ID}/kube-pod-broker-controller:latest
              name: image-cache-update
              command: ["/bin/bash"]
              args:
                - "-ec"
                - |
                  CURR_BUILD=$(gcloud -q builds list --ongoing --filter='tags[]~selkies-image-cache-image-project' 2>/dev/null || true)
                  if [[ -n "$${CURR_BUILD}" ]]; then
                    echo "WARN: Existing update cache update build found, exiting."
                    exit 0
                  fi
                  cd /tmp && tar zxvf /var/run/cloudbuild/cloudbuild.tgz
                  cat cloudbuild.yaml
                  gcloud -q builds submit --config cloudbuild.yaml --substitutions=_PROVISION_MACHINE_TYPE=${_PROVISION_MACHINE_TYPE},_IMAGE_BUILD_REGION=${_IMAGE_BUILD_REGION},_IMAGE_BUILD_ZONE=${_IMAGE_BUILD_ZONE},_EXCLUDE_REGIONS=${_EXCLUDE_REGIONS},_DISK_SIZE_GB=${_DISK_SIZE_GB},_PULL_ALL_GCR=${_PULL_ALL_GCR} || true
              volumeMounts:
                - name: cloudbuild
                  mountPath: /var/run/cloudbuild
              resources:
                requests:
                  cpu: 10m
