#!/bin/sh -e

##########################################################################
#   Function description:
#       Pause until user presses return
##########################################################################

pause()
{
    local junk
    
    printf "Press return to continue..."
    read junk
}


if [ $# -lt 3 ]; then
    cat << EOM

Usage: $0 ufs|msdosfs|cd9660 image-file mount-directory [slice]

Examples:

    Mount a FreeBSD installer USB image:
    
	mount_image ufs FreeBSD-14.3-RELEASE-amd64-memstick.img /mnt 2a
	
    Mount a CD/DVD image:
    
	mount_image cd9660 FreeBSD-10.1-RELEASE-amd64-disc1.iso /mnt

    Mount a FreeDOS USB image, with the filesystem on slice one (/dev/md0s1):
    
	mount_image msdosfs FreeDOS-1.1-memstick-3-30M.img /mnt 1
    
    Mount a FreeDOS floppy disk image with the filesystem on the raw volume
    (no partitions/slices):
    
	mount_image msdosfs fdboot.img /mnt

EOM
    exit 1
fi

fs_type=$1
image=$2
dir=$3
if [ $# = 4 ]; then
    slice="s$4"
else
    slice=""
fi

# Create memory disk from image
md=`mdconfig -f $image`

if [ ! -f $image ]; then
    printf "$0: Error: $image: No such file.\n"
    exit 1
fi

if [ ! -d $dir ]; then
    printf "$0: Error: $dir: No such directory.\n"
    exit 1
fi

ls /dev/$md*
if [ -z "$slice" ]; then
    printf "Slice (1, 2, 2a, etc.) [none] "
    read slice
    if [ -n "$slice" ]; then
	slice=s$slice
    else
	slice=''
    fi
fi

if [ $fs_type = ufs ]; then
    mount=mount
else
    mount=mount_$fs_type
fi
if $mount /dev/$md$slice $dir; then
    cat << EOM

Be sure to unmount using umount_image, not umount, or the memory disk
will not be detached.

EOM
else
    devnum=`echo $md | cut -c 3-`
    mdconfig -d -u $devnum
fi
