#!/bin/sh
#
# Helper script for using a diskfile for the LOWER or UPPER+WORK
# filesystems.
#
# Example use a whole diskfile filesystem as LOWER:
# LOWER=!overlay-diskfile mnt/ disk.img
#
# Example use a diskfile partition 2 as LOWER:
# LOWER=!overlay-diskfile mnt/ disk.img 2
#
# Example use a subtree of a diskfile partition 2 as LOWER:
# LOWER=!overlay-diskfile mnt/some/path disk.img 2
#
# Example use a while diskfile as UPPER and WORK.
# The diskfile is mounted on "mnt".
# UPPER=!overlay-diskfile mnt/some/upper/path disk.img 2
# WORK= mnt/some/work/path

# Helper function to determine the mount offset for the partition, if any
partoffset() {
    local X
    if [ -z "$2" ] ; then
	echo 0
    else
	fdisk -lo Start "$1" | grep -A$2 '^ Start' | \
	    sed '${s|^|512*|;b};d' | bc -l
    fi
}

# Only do something when invoked by overlay-boot
if [ "$ACTION" = "overlay-boot" ] ; then
    DISKFILE="$2"
    # .. and a diskfile is given
    if [ -n "$DISKFILE" ] ; then
	MOUNTPOINT="$(realpath "${1%/*}")"
	PARTITIONINDEX="$3"
	# .. and it's not mounted yet (for this subhost)
	if ! grep -qE "^[^ ]* $MOUNTPOINT" /proc/mounts ; then
	    OFFSET=$(partoffset "$DISKFILE" "$PARTITIONINDEX")
	    mount -ooffset=$OFFSET "$DISKFILE" "$MOUNTPOINT" || exit 1
	fi
    fi
fi
echo "${1#/}"
