#!/usr/bin/env bash
# Run an explicit build command inside the existing non-root Void container.
source "$(dirname -- "${BASH_SOURCE[0]}")/lib.sh"
(( $# > 0 )) || die 'Usage: tools/in-void [--isolated-network] COMMAND [ARGUMENT...]'
fds_network_options=()
if [[ $1 == --isolated-network ]]; then
    fds_network_options=(--unshare-net)
    shift
fi
if [[ ${FDS_OFFLINE:-0} == 1 ]]; then
    fds_network_options=(--unshare-net)
fi
(( $# > 0 )) || die 'Missing command'
check_void_pin
[[ -x $FDS_VOID/masterdir-x86_64/usr/bin/xbps-install ]] || die 'Run make bootstrap first'
(( EUID != 0 )) || die 'Run as a normal user, not root'
fds_cargo_home=${CARGO_HOME:-$HOME/.cargo}
fds_rustup_home=${RUSTUP_HOME:-$HOME/.rustup}
fds_rust_bin=$(dirname -- "$(rustup which rustc)")
[[ -d $fds_cargo_home && -d $fds_rustup_home ]] || die 'Rustup directories are missing; run make bootstrap'
exec bwrap --unshare-user --uid 0 --gid 0 "${fds_network_options[@]}" \
    --bind "$FDS_VOID/masterdir-x86_64" / --dev /dev --proc /proc \
    --bind "$FDS_ROOT" "$FDS_ROOT" --bind "$FDS_VOID/hostdir" /host \
    --bind "$fds_cargo_home" "$fds_cargo_home" \
    --ro-bind "$fds_rustup_home" "$fds_rustup_home" \
    --ro-bind /etc/resolv.conf /etc/resolv.conf \
    --setenv CARGO_HOME "$fds_cargo_home" --setenv RUSTUP_HOME "$fds_rustup_home" \
    --setenv PATH "$fds_rust_bin:/usr/bin:/bin" --setenv XBPS_ARCH x86_64 \
    --chdir "$FDS_ROOT" "$@"
