#!/bin/bash
# Scheduled entry point for the rc channel.
#
# The rc channel builds from the standing `rc` branch in its own worktree, but
# that branch does not exist until the first RC is cut — and a host set up
# before then has no worktree either. This runs from the MAIN checkout, which
# always exists, and makes both conditions non-events: no branch means nothing
# to build, and a missing worktree is created on demand rather than failing
# the unit every five minutes.

set -e

BUILD_ROOT=$(realpath "${BASH_SOURCE[0]%/*}/..")
source "$BUILD_ROOT/helpers/message-helpers.sh"

RC_WORKTREE="${OMARCHY_RC_WORKTREE:-/root/omarchy-pkgs-rc}"
STATE_DIR="${OMARCHY_STATE_DIR:-/root/.state}"

# Nothing queued: the common case. Exit before touching the network.
[[ -f "$STATE_DIR/.sync-needed-rc" ]] || exit 0

git -C "$BUILD_ROOT" fetch --quiet origin rc 2>/dev/null || true

if ! git -C "$BUILD_ROOT" show-ref --verify --quiet refs/remotes/origin/rc; then
  print_info "No rc branch yet — nothing to build (the first RC cut creates it)"
  exit 0
fi

if [[ ! -d "$RC_WORKTREE" ]]; then
  print_info "Creating rc worktree at $RC_WORKTREE..."
  if git -C "$BUILD_ROOT" show-ref --verify --quiet refs/heads/rc; then
    git -C "$BUILD_ROOT" worktree add "$RC_WORKTREE" rc
  else
    git -C "$BUILD_ROOT" worktree add --track -b rc "$RC_WORKTREE" origin/rc
  fi
fi

# The rc branch is rebuilt as master + pins for each cut and force-pushed, so
# this follows with a hard reset rather than a fast-forward pull.
git -C "$RC_WORKTREE" fetch origin rc
git -C "$RC_WORKTREE" reset --hard origin/rc

exec "$RC_WORKTREE/bin/auto-release" rc
