#!/bin/sh
# Copyright 2022 Helmut Grohne <helmut@subdivi.de>
# SPDX-License-Identifier: MIT
#
# This is a mmdebstrap customize hook that adds a systemd-generator that causes
# 9p 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, pass
# -virtfs local,security_model=none,mount_tag=$SOMETAG,path=$SOMEDIR
# Note that the linux-image-cloud-* does not include a 9p driver.

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

UNITDIR=$1

modprobe 9pnet_virtio || exit 0

for tagfile in /sys/bus/virtio/devices/*/mount_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=9p mount for tag $tag

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