#!/bin/sh

# Idea/starting point originally found in Ubuntu forums (see comments below)
# and then heavily modified by 
# Bryan F. Ritter
# BryanFRitt@HotMail.com

#http://ubuntuforums.org/showthread.php?t=679762&page=11
#http://ubuntuforums.org/showpost.php?p=6713403&postcount=116
#modified like stated in
#http://ubuntuforums.org/showthread.php?t=679762&page=13
#http://ubuntuforums.org/showpost.php?p=6808633&postcount=121

# Moved to separate file, was originally in ~/.bashrc

# adds img support...
# http://qgqlochekone.blogspot.com/2008/04/iso-linux-debian-venenux-tools.html

# plus some other changes
#  the ability to have a mount point with spaces
#  different usage message

# 2013-05-29_We
#  added '-r' in mount commands to take care of readonly warning, 
#  these are supposed to be read only anyway.

# Possible Improvements:
# It could probably be rewritten to reduce elses and ifs, and be easier upgradable if a new format comes along.
# TODO: There could be an option to mount right in the current folder # see getopt, getopts, ...
# TODO: modify message changing 'FILE.iso' to reflect that it can take file times other than iso
# TODO: merge two identical help usage messages into one variable, _usagephrase=...
# NOTE: originally tested in 'bash', found to work in 'sh'

#miso() #mount iso file
#{

#_mountpoint="/media/Mounted_iso/Default"

# http://www.unix.com/shell-programming-scripting/40360-remove-file-extension.html
# Should I leave on the extension?
# basename gets rid of the ./
#_mountname=$(echo basename $2 | sed 's/\(.*\)\..*/\1/')
_mountname=$(basename "$2")
# If you want every disc mount to be at the same place you can do something like...
#_mountname=Common

_mountpoint="/media/Mounted_iso/${_mountname}"

#sudo mkdir -p "${_mountpoint}"
#echo ${_mountpoint}

_nowmountedphrase="'${_mountname}' is now mounted.\nTo switch to it\n cd '${_mountpoint}/'\nTo switch back\n cd -\n or \n cd $(pwd)"
_logmountedphrase="$(pwd)/${_mountname}\nwas mounted at\n${_mountpoint}\non\n$(/bin/date +"%F_%H:%M:%S.%N_                     %p_%a_Week+%V_(%::z%Z)")\n\n"
#echo ""
#echo ""
#echo -ne "${_nowmountedphrase}" && sudo sh -c "printf '${_logmountedphrase}' >> '${_mountpoint}_MountInfo.txt'"

#_nowmountedaction=$(cd _mountpoint)
#_alreadymountedphrase=

# if you don't want to verify if the file name ends in a .iso (case insensitive, -i) remove
# && [ -n "$(echo "$2" | grep -i .iso$)" ]

if [ -z "$1" ]; then
    echo " usage:"
    echo "   '$0' -m 'FILE.iso' to   mount 'FILE.iso' at   '${_mountpoint}'"
    echo "   '$0' -u 'FILE.iso' to unmount 'FILE.iso' from '${_mountpoint}'"
    echo "   Where 'FILE.iso' is the name, or path and name, of the  image file to mount"
    echo "   The image file can be a *.iso, *.nrg, *.img, or a *.dmg file"
    echo "   remember the argument -m or -u"
elif [ "$1" = "-u" ]; then
    if [ -n "$2" ]; then
        if [ -d  "${_mountpoint}" ]; then
            sudo umount "${_mountpoint}" && echo "'${_mountpoint}' is now unmounted."
            echo " Would you like to delete the folder? '${_mountpoint}'" && echo " 'y', or 'yes', 'ok' to delete (case insensitive)"
            read DELETEDIRYN
            case $DELETEDIRYN in
            [Yy] | [Yy][Ee][Ss] | [Oo][Kk] ) 
                echo " Ok, deleting directory '${_mountpoint}'"; 
                sudo rmdir "${_mountpoint}";
                ;;
            [Nn] | [Nn][Oo] | [Nn][Oo][Pp][Ee] ) 
                echo " OK, leaving alone directory '${_mountpoint}'";
                ;;
            * ) 
                echo " defaulting to leaving alone directory '${_mountpoint}'";
                ;;
            esac

            echo " Would you like to delete the log file? '${_mountpoint}_MountInfo.txt'" && echo " 'y', or 'yes', 'ok' to delete (case insensitive)"
            read DELETEDIRYN
            case $DELETEDIRYN in
            [Yy] | [Yy][Ee][Ss] | [Oo][Kk] ) 
                echo " Ok, deleting file '${_mountpoint}_MountInfo.txt'"; 
                sudo rm "${_mountpoint}_MountInfo.txt";
                ;;
            [Nn] | [Nn][Oo] | [Nn][Oo][Pp][Ee] ) 
                echo " OK, leaving alone file '${_mountpoint}_MountInfo.txt'";
                ;;
            * ) 
                echo " defaulting to leaving alone file '${_mountpoint}_MountInfo.txt'";
                ;;
            esac

          else
            echo " directory not found: '${_mountpoint}'"
        fi
    else
        echo " -u requires the mountname argument"
    fi
elif [ "$1" = "-m" ]; then
    # http://www.tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html
    # [ -r FILE ]	True if FILE exists and is readable.
    # [ -z STRING ]	True of the length if "STRING" is zero.
    # [ -n STRING ] or [ STRING ]	True if the length of "STRING" is non-zero.
    # TODO: combine these 'if [ -r "$2" ]' into one 'if [ -r "$2" ]' ...
    if [ -r "$2" ] && echo "$2" | grep -i -q .iso$ ; then
        sudo mkdir -p "${_mountpoint}"
    if [ "$(find "${_mountpoint}" | wc -w)" -ne 0 ]; then
        printf " error: '%s' is not empty, \ntry %s -u '%s' to unmount it" "${_mountpoint}" "$0" "${_mountpoint}" >&2
    else
        sudo mount -r -o loop "$2" "${_mountpoint}" && printf " %s" "${_nowmountedphrase}" && sudo sh -c "printf '${_logmountedphrase}' >> '${_mountpoint}_MountInfo.txt'"
        # && echo -ne "'$2'\n is now mounted.\nTo switch to it\n cd '${_mountpoint}'\nTo switch back\n cd -" && cd "${_mountpoint}"
    fi
    elif [ -r "$2" ] && echo "$2" | grep -i -q .nrg$ ; then
        sudo mkdir -p "${_mountpoint}"
        if [ "$(find "${_mountpoint}" | wc -w)" -ne 0 ]; then
            printf " error: '%s' is not empty, \ntry %s -u  '%s' to unmount it" "${_mountpoint}" "$0" "${_mountpoint}" >&2
            else  #http://forums.whirlpool.net.au/forum-replies-archive.cfm/499696.html
            sudo mount -r -o loop,offset=307200 "$2" "${_mountpoint}" && printf " %s" "${_nowmountedphrase}" && sudo sh -c "printf '${_logmountedphrase}' >> '${_mountpoint}_MountInfo.txt'"
            #echo -e "'$2'\n is now mounted.\nTo switch to it\n cd '${_mountpoint}'\nTo switch back\n cd -" && cd "${_mountpoint}"
        fi
    elif [ -r "$2" ] && echo "$2" | grep -i -q .dmg$ ; then
        sudo mkdir -p "${_mountpoint}"
        if [ "$(find "${_mountpoint}" | wc -w)" -ne 0 ]; then
            printf " error: '%s' is not empty, \ntry %s -u  '%s' to unmount it" "${_mountpoint}" "$0" "${_mountpoint}" >&2
            else
            
            # see also https://viaforensics.com/computer-forensics/mount-dmg-file-mac-disk-image-linux.html
            # How to mount a .dmg file (Mac Disk Image) in Linux
            # is the image compressesed? ... file filename.dmg
            # VAX COFF
            # dmg2img -i stage2-decrypted.dmg -o stage2-decrypted-uncompressed.img
            # Then run this again...
            # TODO: make this program do this automatically

            # see also, http://www.eonlinegratis.com/2013/how-to-mount-a-hfs-partition-in-ubuntu-as-readwrite/#sthash.6KrV5Csa.dpbs
            # "Do you have the hfsutils or hfsplus depending on which type of hfs it is?" #http://www.linuxquestions.org/questions/linux-newbie-8/how-to-mount-hfs-drive-926824/
            #mount -t hfs <blah blah>, mount -t hfsplus <blah blah> #http://www.linuxquestions.org/questions/linux-software-2/mounting-hfs-volumes-under-linux-521189/
            #mount -t ufs -o ufstype=44bsd,ro /dev/sda10 /mac_gerald # same url as above
            #mount -t hfsplus /dev/sdb1 /mnt/external # http://www.tuxradar.com/answers/700
            # NOT TESTED! (didn't have any files of this type to test script on when making this)
            # http://baghira.sourceforge.net/dmg.htm
            # http://ubuntuforums.org/showthread.php?t=1155734
            # http://en.wikipedia.org/wiki/HFS_Plus
            # which one of these two should I do, or should I do something else? hfs vs hfsplus ?
            #sudo mount -r -t hfsplus -o loop "$2" "${_mountpoint}" || sudo mount -r -t hfs -o loop "$2" "${_mountpoint}" && echo -e "'$2'\n  is mounted. To switch to it\ncd '${_mountpoint}'"
            sudo mount -r -t hfs -o loop "$2" "${_mountpoint}" || sudo mount -r -t hfsplus -o loop "$2" "${_mountpoint}" && printf " %s" "${_nowmountedphrase}" && sudo sh -c "printf '${_logmountedphrase}' >> '${_mountpoint}_MountInfo.txt'"
            #echo -e "'$2'\n is now mounted.\nTo switch to it\n cd '${_mountpoint}'\nTo switch back\n cd -" && cd "${_mountpoint}"
        fi
    #http://qgqlochekone.blogspot.com/2008/04/iso-linux-debian-venenux-tools.html
    elif [ -r "$2" ] && echo "$2" | grep -i -q .img$ ; then
        sudo mkdir -p "${_mountpoint}"
        if [ "$(find "${_mountpoint}" | wc -w)" -ne 0 ]; then
            printf " error: '%s' is not empty, \ntry %s -u to unmount it" "${_mountpoint}" "$0" >&2
            else  
            sudo mount "$2" "${_mountpoint}" -o loop=/dev/loop0,user && printf " %s" "${_nowmountedphrase}" && sudo sh -c "printf '${_logmountedphrase}' >> '${_mountpoint}_MountInfo.txt'"
        fi
            #http://www.ehow.com/how_6525143_mount-mdf-linux.html
            #http://sathyasays.com/2007/12/15/mounting-iso-and-mdsmdf-files-in-linux/
            #"The command in the blog post will not work for mdf files. The author probably had iso9660 files that were simply mislabeled as mdf."
            #cdemu-userspace #AcetoneISO
        # elif [ -r "$2" ] && [ -n "$(echo "$2" | grep -i .mdf$)" ]; then
        #  sudo mkdir -p "${_mountpoint}"
        #    if [ $(find "${_mountpoint}" | wc -w) -ne 0 ]; then
        #      echo -e "error: '${_mountpoint}' is not empty, \ntry $0 -u to unmount it" >&2
        #    else
        #      sudo mount -r -o loop -t iso9660 "$2" "${_mountpoint}"  && echo -e " ${_nowmountedphrase}" && sudo sh -c "printf '${_logmountedphrase}' >> '${_mountpoint}_MountInfo.txt'"
        #    fi
    else
            echo " error: '$2' is not a readable *.iso, *.nrg, *.img, nor a *.dmg file." >&2
    fi
else
    echo " usage:"
    echo "   '$0' -m 'FILE.iso' to   mount 'FILE.iso' at   '${_mountpoint}'"
    echo "   '$0' -u 'FILE.iso' to unmount 'FILE.iso' from '${_mountpoint}'"
    echo "   Where 'FILE.iso' is the name, or path and name, of the  image file to mount"
    echo "   The image file can be a *.iso, *.nrg, *.img, or a *.dmg file"
    echo "   remember the argument -m or -u"
fi

