#!/bin/sh
set -eu

interval="${UNIDESK_CICD_BRANCH_FOLLOWER_INTERVAL_SECONDS}"
timeout="${UNIDESK_CICD_BRANCH_FOLLOWER_TIMEOUT_SECONDS}"

while true; do
  started_at=$(date -Iseconds)
  echo "branch-follower loop started ${started_at}"
  cd /work
  rm -rf /work/unidesk
  /etc/unidesk-cicd-branch-follower/sync-source.sh \
    "${UNIDESK_CONTROLLER_SOURCE_REPOSITORY}" \
    "${UNIDESK_CONTROLLER_SOURCE_BRANCH}" \
    "${UNIDESK_CONTROLLER_SOURCE_SNAPSHOT_PREFIX}" \
    "/cache/${UNIDESK_CONTROLLER_SOURCE_REPOSITORY}.git"
  git clone --branch "${UNIDESK_CONTROLLER_SOURCE_BRANCH}" "/cache/${UNIDESK_CONTROLLER_SOURCE_REPOSITORY}.git" /work/unidesk
  cp /etc/unidesk-cicd-branch-follower/cicd-branch-followers.yaml /work/unidesk/config/cicd-branch-followers.yaml
  cd /work/unidesk
  bun scripts/cli.ts cicd branch-follower run-once --all --confirm --in-cluster --config config/cicd-branch-followers.yaml --timeout-seconds "${timeout}" || true
  echo "branch-follower loop finished $(date -Iseconds)"
  cd /work
  sleep "${interval}"
done
