#!/bin/sh

IMG="$1"
MOUNTPOINT="$HOME/guest_fs"
DIR2CHECK="$MOUNTPOINT/boot"

export LANG=C
export LIBGUESTFS_TRACE=1

echo 'Creat mount point...'
mkdir "$MOUNTPOINT"

echo "Mount $IMG per guestmount..."
guestmount -a "$IMG" -m /dev/sda1 "$MOUNTPOINT"
echo "List content of $DIR2CHECK..."
ls -l "$DIR2CHECK"

cleanup() {
	ret=0
	if grep $MOUNTPOINT /etc/mtab >/dev/null; then
		echo "Unmount $MOUNTPOINT..."
		fusermount -u "$MOUNTPOINT"
	else
		echo 'Failed to mount image, nothing to unmount.'
		ret=1
	fi
	if [ -d "$MOUNTPOINT" ]; then
		echo 'Drop mount point...'
		rmdir "$MOUNTPOINT"
	fi
	if [ $ret != 0 ]; then
		echo "Terminated with error"
	fi	
	exit $ret
}

trap cleanup EXIT TERM INT HUP
