#/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

N_NBD=16
img=tmp/deploy/images/core-image-base-zynq.sdimg
dir=rootfs
p=2

sudo modprobe nbd max_part=$N_NBD

if [ -z "$1" ]; then
    dev=""
    for d in /sys/class/block/nbd*; do
	if [ "`cat $d/size`" = "0" ]; then
	    dev=`basename $d`
	    break
	fi
    done
    if [ -z "$dev" ]; then
	echo "$0: Couldn't find free nbd device" >&2
	exit 2
    fi
fi

sudo qemu-nbd -c /dev/$dev $img
mkdir -p $dir
sudo mount /dev/${dev}p$p $dir
echo Mounted /dev/${dev}p$p
