#!/bin/sh

# 19/04/2014, author: Maxim Suhanov

# Changes:
# 05/05/2014: don't call the /sbin/mount.<filesystem> helper.
# 06/05/2014: handle JFS too.
# 11/09/2014: mount Ext3 as Ext4 (without journal), disable btrfs support.

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

list_volumes()
{
	imgdev="$(findmnt -o SOURCE -n /image | head -n 1)"
	blkid -o device | grep -vE "^(/dev/loop([[:digit:]]+|/.*)|$imgdev)$"
}

get_fstype()
{
	fstype=`blkid -o value -s TYPE "$1"`
	case "$fstype" in
		ext3) fstype="ext4";; # Mount Ext3 as Ext4
		btrfs)
			fstype="" # No btrfs support today, sorry
			echo "$1 contains btrfs, which is not supported" >&2
		;;
	esac
	echo "$fstype"
}

get_mountopts()
{
	opts='ro,loop,noexec' # Do not remove "loop"!
	case "$1" in
		ntfs) opts="$opts,nls=utf8";;
		vfat) opts="$opts,utf8";;
		jfs)  opts="$opts,iocharset=utf8";;
		ext3|ext4) opts="$opts,noload";;
	esac
	echo "$opts"
}

get_mountpoint()
{
	mountpoint="/mnt/$(basename "$1")/"
	echo "$mountpoint"
	mkdir "$mountpoint" 2> /dev/null
}

mount_forensic()
{
	for volume in `list_volumes`; do
		volume_fs="$(get_fstype "$volume")"
		case "$volume_fs" in
		swap|*_member|crypto_*|"")
			continue;;
		esac
		opts="$(get_mountopts "$volume_fs")"
		mountpoint="$(get_mountpoint "$volume")"
		[ -n "$mountpoint" ] || continue
		mountpoint -q "$mountpoint" && continue
		# We don't expect any spaces in a devname but...
		cmd="mount -i -t $volume_fs -o $opts"
		echo "Executing: $cmd \"$volume\" \"$mountpoint\""
		$cmd "$volume" "$mountpoint"
	done
}


mount_forensic
