#!/usr/bin/env bash
# Independent host-tool prefix, so image construction does not mutate xbps-src.
source "$(dirname -- "${BASH_SOURCE[0]}")/lib.sh"
[[ $# == 0 ]] || die 'Usage: tools/prepare-image-tools'
cd "$FDS_ROOT"
use_xbps
check_void_pin
root="$FDS_ROOT/.host/image-tools"
cache="$FDS_ROOT/out/cache/image-tools"
mkdir -p "$root/var/db/xbps/keys" "$root/config" "$cache" out/manifests
exec 9>out/.image-tools.lock
flock 9
cp "$FDS_VOID/common/repo-keys/"*.plist "$root/var/db/xbps/keys/"
if [[ ! -x $root/usr/bin/mkfs.erofs || ! -x $root/usr/bin/mformat || ! -x $root/usr/bin/mkfs.fat || ! -x $root/usr/bin/mke2fs ]]; then
    [[ ${FDS_OFFLINE:-0} != 1 ]] || die 'Missing frozen image tools; restore the complete input snapshot'
    bwrap --unshare-user --uid 0 --gid 0 --ro-bind / / \
        --bind "$root" "$root" --bind "$cache" "$cache" --dev /dev --proc /proc \
        env XBPS_ARCH=x86_64 XBPS_TARGET_ARCH=x86_64 \
        "$FDS_XBPS/xbps-install" -r "$root" -C "$root/config" -c "$cache" \
        -i -R https://repo-default.voidlinux.org/current -SyU erofs-utils dosfstools mtools e2fsprogs
fi
XBPS_ARCH=x86_64 xbps-query -r "$root" -l >out/manifests/image-tool-packages.txt
find "$cache" -maxdepth 1 -name '*.xbps' -print0 | sort -z | xargs -0 sha256sum >out/manifests/image-tool-inputs.sha256
tools/in-image-tools mkfs.erofs --version
printf 'PASS: project-local EROFS and FAT image tools prepared\n'
