#!/bin/bash
# imgmount
#
# Mount partitions in an image file to /mnt/raspberry/loop<n>p<m>
#
# See https://gist.github.com/OhMeadhbh/68a31d86dba2716e74c4 for license info.
#
# Remember to run me as root passing the name of the image file as a parameter.
# Also, try to remember the name of the loopback device it prints out; you'll
# need it for the imgumount command. Running it thusly puts the loopback device
# in the variable $LODEV:
#
#   LODEV=`sudo imgmount ~/2014-09-09-wheezy-raspbian.img` ; echo $LODEV
#
# so after you're finished you can run imgumount like this:
#
#  sudo imgumount $LODEV

IMGFILE=$1
LODEV=`losetup -f --show $IMGFILE`
DEVNO=`echo $LODEV | rev | cut -b 1`

for PART in $( fdisk -l $LODEV| tr -d '*' | awk '/^\/dev/ { print count++ ":" $2 }' ); do
  MNTDIR="/mnt/raspberrypi/loop${DEVNO}p`echo $PART | cut -f 1 -d :`"
  OFFSET="`echo \"$PART\" | cut -f 2 -d :`"
  mkdir -p $MNTDIR > /dev/null 2>&1
  mount -o offset=$(( 512 * `echo $OFFSET` )),loop $LODEV $MNTDIR
done

echo $LODEV
