#!/bin/sh
# Copyright 2023-2026 Helmut Grohne <helmut@subdivi.de>
# SPDX-License-Identifier: MIT
#
# This is a mmdebstrap customize hook that adds a systemd-generator that causes
# virtiofs filesystems to be automatically mounted to /media/$SOMETAG during
# boot. You can enable it by passing the containing directory to --hook-dir.
# In order to add a 9p filesystem to your VM, launch a virtiofsd server and
# pass the following options to qemu
#     -m 4G
#     -object memory-backend-file,id=mem,size=4G,mem-path=/dev/shm,share=on
#     -numa node,memdev=mem
#     -device "vhost-user-fs-pci,queue-size=1024,chardev=virtiofs,tag=$SHARE_TAG"
#     -chardev "socket,id=virtiofs,path=$SHARE_SOCKET"
# This works with a cloud flavoured kernel image.

set -eu

TARGET=$1

if test "${MMDEBSTRAP_VERBOSITY:-1}" -ge 3; then
	set -x
fi

GENERATOR_PATH="$TARGET/etc/systemd/system-generators/virtiofs-generator"
mkdir -p "${GENERATOR_PATH%/*}"
cat >"$GENERATOR_PATH" << 'ENDOFGENERATOR'
#!/bin/sh

UNITDIR=$1

for tagfile in /sys/fs/virtiofs/*/tag; do
	tag=$(cat "$tagfile") || continue
	test -z "$tag" && continue
	mountpoint="/media/$tag"
	mkdir -p "$mountpoint"
	unitname="$(systemd-escape -p "$mountpoint").mount"
	cat > "$UNITDIR/$unitname" <<ENDOFUNIT
[Unit]
Description=virtiofs mount for tag $tag

[Mount]
What=$tag
Where=$mountpoint
Type=virtiofs
ENDOFUNIT
	mkdir -p "$UNITDIR/remote-fs.target.wants"
	ln -s "../$unitname" "$UNITDIR/remote-fs.target.wants/$unitname"
done
ENDOFGENERATOR
chmod 755 "$GENERATOR_PATH"
