#!/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

if git switch --quiet --detach -- "refs/remotes/origin/${FORK_BRANCH}"; then
   printf '%s\n' "switch ${displaypath:-${PWD}} (origin: ${submodule_url}) -> origin/${FORK_BRANCH}"
fi
