#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
set -Eeuo pipefail
(( EUID == 0 )) || exit 1
project=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)
if [[ ${1:-} != --namespace ]]; then
    exec unshare --mount --pid --fork --kill-child=SIGKILL --propagation private /bin/bash "$0" --namespace "$@"
fi
shift
build_uid=${1:?}
build_gid=${2:?}
apt_cache=${3:-enabled}
[[ $apt_cache == enabled || $apt_cache == disabled ]]
[[ $build_uid =~ ^[0-9]+$ && $build_gid =~ ^[0-9]+$ ]]
(( build_uid > 0 && build_gid > 0 ))
work="$project/build"
root="$work/controller"
[[ ! -L $work && ! -L $root ]]
exec 9>"$work/operation.lock"
flock --nonblock 9
if [[ ! -f $work/controller-bootstrap.complete ]]; then
    if [[ -e $root ]]; then
        echo 'Incomplete controller. Inspect before retrying.' >&2
        exit 1
    fi
    debootstrap --arch=amd64 --variant=minbase --include=ca-certificates,debian-archive-keyring,python3 \
      --keyring=/usr/share/keyrings/debian-archive-keyring.gpg --force-check-sig \
      trixie "$root" https://snapshot.debian.org/archive/debian/20261026T000000Z/
    touch "$work/controller-bootstrap.complete"
fi
exec /bin/bash "$project/tools/lib/enter-root" "$root" "$work" root /bin/bash /work/input/configure-controller "$build_uid" "$build_gid" "$apt_cache"
