#/bin/sh
#
# Copyright (C) 2015-2016 ilbers GmbH
#
# Calls sudo from within the script, since ISARROOT is dropped from PATH if
# the script is called with sudo.

set -e

dir=rootfs

if [ -n "$1" ]; then
    dev=/dev/nbd$1p2
else
    case `mount |grep "^/dev/nbd.* on \`pwd\`/$dir type " |wc -l` in
	0)
	    echo "$0: ERROR: Couldn't find mounted nbd device" >&2
	    exit 2
	    ;;
	1)
	    line=`mount |grep "^/dev/nbd.* on \`pwd\`/$dir type "`
	    dev=`echo $line |sed 's,^\(/dev/nbd[^ ]*\) .*$,\1,'`
	    d=`echo $line |sed 's,^/dev/nbd[^ ]* on \(.*\) type .*$,\1,'`
	    ;;
	*)
	    echo "$0: ERROR: Found too many nbd devices" >&2
	    exit 2
	    ;;
    esac
fi

sudo umount $dev
sudo qemu-nbd -d $dev
