#!/bin/bash

## Copyright (C) 2026 - 2026 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

## AI-Assisted

## A missing fork branch must exit 0 (not fail the foreach) so
## submodules without a matching branch keep the parent's SHA pin.

set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit
shopt -s shift_verbose

if [ -z "${FORK_BRANCH:-}" ]; then
   printf '%s\n' "${BASH_SOURCE[0]}: \$FORK_BRANCH not set; call from ci/checkout-fork-submodule-branches" >&2
   exit 64
fi

submodule_url="$(git remote get-url origin 2>/dev/null || printf '%s' '<no-origin>')"

if ! fetch_log="$(git fetch origin -- "${FORK_BRANCH}" 2>&1)"; then
   printf '%s\n' "no-ref ${displaypath:-${PWD}} (origin: ${submodule_url}): ${fetch_log}"
   exit 0
fi

## The fetch succeeded (branch exists), so check it out. Detach onto FETCH_HEAD --
## which 'git fetch origin -- BRANCH' always sets -- rather than
## 'refs/remotes/origin/BRANCH': a submodule whose remote refspec does not populate
## 'refs/remotes/origin/*' (e.g. a single-branch submodule clone, as grml-debootstrap
## is here) leaves that tracking ref absent, which used to abort the switch. FETCH_HEAD
## is always valid after the fetch, so every submodule with a matching fork branch is
## checked out uniformly -- no per-submodule special-casing. 'errexit' surfaces a
## genuine switch failure.
git switch --quiet --detach FETCH_HEAD
printf '%s\n' "switch ${displaypath:-${PWD}} (origin: ${submodule_url}) -> origin/${FORK_BRANCH}"
