#!/bin/bash

showHelp=0

valImg=""
valMnt=""

while [ "$1" != "" ]; do
	case "$1" in
	  -h | --help | --usage)
		showHelp="1"
		;;
	  --no-sudo )
		noSudo="1"
		;;
	  *)
		if [ "$valImg" == "" ]; then
			valImg="$1"
		else
			if [ "$valMnt" == "" ]; then
				valMnt="$1"
			fi
		fi
		;;
	esac
	shift
done

if [ "$showHelp" == "1" ]; then
	echo "Usage: mountimg [IMAGE_FILE [MOUNT_DIR]]"
	echo "Mounts partitions from device image file"
	echo " "
	echo "Common options:"
	echo "  image_file  Source file where are requested partitions stored."
	echo "  mount_dir   Where to place target directory with partitions mountpoints."
	echo "              Default: /media"
	echo " "
	echo "General options:"
	echo "  -h, --help, --usage  This help."
	echo "  --no-sudo            When root privileges are necessary, application forces"
	echo "                       sudo command. If you want to disable this feature, use"
	echo "                       this prefix."
	echo " "
	echo "(c) 2014-2019 LUnet Studio, http://LUnet.Studio"
	exit
fi


sc=""
if [ "$USER" != "root" ] && [ "$noSudo" != "1" ]; then
	sc="sudo "
	sudo echo "" > /dev/null
fi


if [ "$valImg" == "" ]; then
	read -p "Source device image file: " valImg
fi
#if [ "$valMnt" == "" ]; then
#	read -p "Target mountpoint directory: " valMnt
#fi


if [ "$valMnt" == "" ]; then
	valMnt="/media"
fi
if [ "$valImg" != "" ]; then
	valUid=`id -u`
	valGid=`id -g`
	
	pathImg="${valImg// /_}"
	pathImg="${pathImg//"/"/ }"
	arrDirName=($pathImg)
	i=${#arrDirName[*]}
	let i--
	valMnt="${valMnt}/${arrDirName[$i]}"
	
	cmdFdisk=`${sc}fdisk -l $valImg`
	valFdisk=`echo "${cmdFdisk//"${valImg}"/PART:}"`
	y=0
	while [ $y -lt 10 ]; do
		valFdisk="${valFdisk//  / }"
		let y++
	done
	
	${sc}mkdir $valMnt
	${sc}chown ${valUid}:${valGid} $valMnt
	
	numPos=1
	valLine="."
	while [ $numPos -lt 99 ]; do
		valLine=`echo "$valFdisk" | grep "PART:${numPos}"`
		if [ "$valLine" != "" ]; then
			arrLine=($valLine)
			valStart="${arrLine[1]}"
			numBlocks=`expr $valStart \\* 512`
			${sc}mkdir $valMnt/part-$numPos
			${sc}chown ${valUid}:${valGid} $valMnt/part-$numPos
			${sc}mount -o loop,rw,offset=$numBlocks $valImg $valMnt/part-$numPos
		fi
		let numPos++
	done
	
	echo "${valImg} mounted in ${valMnt}."
else
	echo "Required parameters was not specified."
	echo "Try 'mountimg --help' for more information."
fi
