######################
# USB functions and menus

function drive_mountcheck ()
{
# Check to see whether it exists ;-)
grep /media/usb"$MOUNTPOINT" /etc/mtab   > /dev/null 2>&1
if [ $? -ne 0 ] ; then
        echo
        info-col
        echo "  /media/usb"$MOUNTPOINT" is not mounted, according to mtab"
        echo "  Did you type the right number?"
        echo
        sleep 5
        f-usb
fi
}

function f-usb ()
{
clear
fig-col
bold
figlet "  inx      usb"
head-col
echo "  Access your mounted usb devices"
echo
info-col
echo "  When usb devices are plugged in, you should see some lines 
  of output text at the foot of the screen."
echo
head-col
echo "  Refresh this page by hitting <enter> to see the mount point in /media."
info-col
echo
echo "  Mount Point"
bold
green
echo

usbshowmounts="$(mktemp)"
grep /media/usb /etc/mtab | cut -f 2 -d" " > "$usbshowmounts"
for show in $(cat "$usbshowmounts") ; do echo "  $show" ; done # To make output indent two spaces
rm "$usbshowmounts"

echo
info-col
echo "  Choose the device you want to access by usb number."
echo "  For example, \"0\" for /media/usb0 "
echo
head-col
echo "  d: Go to the hard drive menu."
echo "  e: Eject and unmount a device."
echo "  f: Flip colours."
echo "  m: INX main menu."
echo "  x: Give me a command prompt."

f-ttynum
read -s -n 1 MOUNTPOINT

case "$MOUNTPOINT" in
	[0-7] )
	drive_mountcheck
	f-access
	;;
	d)
	f-discmount
	;;
	e)
	MOUNTPOINT=
	f-eject
	f-usb
	;;
	f)
	export CALL=usb
	f-switch
	;;
	m)
	f-menu
	;;
	x)
	clear
	f-prompt
	;;
	*)
	f-usb
	;;
esac

}

# This stuff only works with "usbmount"

function doublecheck ()
{
# Check to see whether it exists ;-)
grep /media/usb"$CHECK" /etc/mtab   > /dev/null 2>&1
if [ $? -ne 0 ] ; then
        echo
        echo "  /media/usb"$CHECK" is not mounted, according to mtab"
        echo "  Did you type the right number?"
        echo
        sleep 5
        f-usb
fi
}

function f-eject ()
{

echo
# See if there are actually any usb devices mounted as /media/usb* in /media ( /etc/mtab)

grep /media/usb /etc/mtab   > /dev/null 2>&1
if [ $? -ne 0 ] ; then
	echo "  You don't seem to have any usb devices auto-mounted, according to mtab"
	sleep 3
	f-usb
fi

# If we haven't just used/accessed a device, then ask...
# Otherwise use the number we have already. (from f-access)

if [ "$MOUNTPOINT" = "" ] ; then
    echo "  Type the number of the device to eject - for instance 1 for /media/usb1"
    read -s -n 1 "EJECT"
	CHECK="$EJECT"
	doublecheck
        eject /media/usb"$CHECK" 2> /dev/null # hardy eject wants to "open" a non-existent tray
	echo -e "\n  Unmounting and ejecting... please wait"
	sleep 3 # not sure this is needed but lights flash for a while...
else
	CHECK="$MOUNTPOINT"
	doublecheck
	eject /media/usb"$CHECK" 2> /dev/null 
	echo -e "\n  Unmounting and ejecting... please wait"
	sleep 3 
fi
	
# Check mtab to see if the device actually unmounted and ejected

grep /media/usb"$CHECK" /etc/mtab   > /dev/null 2>&1
if [ $? -ne 0 ] ; then
	# OK, grep can't find it in /etc/mtab so it must be unmounted...
        green ; bold 
        echo -e "\n  It is now safe to remove the device that was mounted at /media/usb"$CHECK""
        white
        sleep 3
else
	# Something wicked happened, or didn't happen...
        red ; bold 
        echo -e "\n  Your device seems not to have safely unmounted - please check"
        echo "  if it is still shown mounted in the usb menu. Hit <enter> to see."
        white
        read
fi
        f-usb
}

# We get $MOUNTPOINT from f-usb

function f-access ()
{
clear ; unbold
head-col
echo "  Type the number for the access method you want."

info-col

cat <<EOACCESS

  1: Midnight Commander (mc)
  2: Vi File Manager    (vifm)
  3: Linm File Manager  (linm)
  4: Just give me a shell prompt at the mountpoint

  5: Open the mountpoint in the music player (mocp)

EOACCESS

fig-col

echo "  e: Unmount and eject my device safely"
echo

head-col

echo "  Any other key returns to the usb menu."

# Print tty number right edge of terminal
f-ttynum

read -s -n 1 ACCESS

case "$ACCESS" in

	1)
	cd "/media/usb"$MOUNTPOINT"" && f-sup && mc && cd 
	;;
	2)
	cd "/media/usb"$MOUNTPOINT"" && f-sup && vifm && cd 
	;;
	3)
	cd "/media/usb"$MOUNTPOINT"" && f-sup && linm && cd 
	;;
	4)
	clear
	head-col
	echo
	echo "  OK - this is a subshell. Type exit when you are finished"
	echo "  and you will be back in "$HOME". You can then unmount your"
	echo "  device. Don't forget that you are using this subshell," 
	echo "  or the device may show \"busy!\" and refuse to unmount."
	echo
	cd "/media/usb"$MOUNTPOINT"" && white && unbold && /bin/bash && cd 
	;;
	5)
	f-sup ; mocp "/media/usb"$MOUNTPOINT"" && pkill mocp && cd
	;;
	e)
	f-eject
	;;
	*)
	f-usb
	;;

esac

f-access

}

#######################################
# Hard drive mount/umount/access menus

f-discmount ()
{
unbold ; clear # In case of clock - else clock is coloured.
bblack ; fig-col 
figlet "  hard drives"
mkdir -p $HOME/.drivinx
DRIVETEMP="$HOME/.drivinx"

# Clobbers /tmp files once no longer needed
cleanup () { rm -rf $DRIVETEMP ; }

info-col

printf "  " # In case of sudo password request - redundant on default inx :-)

# Show this once, if relevant
if ! [ -f $HOME/.nodisc ] ; then
    if ! sudo fdisk -l | grep /dev | egrep -v "(swap|Ext)" > /dev/null 2>&1 ; then
        echo -e "\n  Fdisk can't find any accessible drives or file systems other than / ..."
        echo -e "  Maybe you are running INX on a discless box,"
        echo -e "  or a virtual machine from the ISO image?\n"
        touch $HOME/.nodisc
    fi
fi

# Gives results of form "/dev/sda1" etc.
DEVICES=$(sudo fdisk -l \
    | egrep -v "(Disk|Ext|swap)"   \
    | grep /dev           \
    | awk '{print $1}'    )
    
# How many accessible devices found?

NUMBER_OF_DEVICES=$(echo $DEVICES | wc -w)

head-col

    echo -e "\n  Type this number:\tTo access:\tMounted on:\n"
	
info-col
	
    COUNTER=0
    # Root is always root... indicate  / as "zero" with "inx".
    # Tried "$HOSTNAME" (more generic), but length alters tabbing ...
    echo "/" > $DRIVETEMP/device"$COUNTER"
    echo "/" > $DRIVETEMP/mountpoint"$COUNTER"
    echo "/" > $DRIVETEMP/existing"$COUNTER"
    echo -e "\t${COUNTER}\t\t      inx  \t/"

    if [ "$DEVICES" != "" ] ; then # If fdisk finds nothing, don't do this 'for' loop...
    for each in $DEVICES
	do
      COUNTER=$((( $COUNTER +1 )))
	  # Show mountpoints in /mnt and /media that are mounted already	
	  NOTIFY=$(grep $each /etc/mtab | egrep "(/mnt|/media)" | tail -1 | awk '{print $2}')
	  echo -e "\t${COUNTER}\t\t${each}\t${NOTIFY}"
	  # Put default mountpoint options somewhere cosy and give them a home...
	  echo $each > $DRIVETEMP/device"$COUNTER"
	  if [ $NOTIFY ] ; then
              echo $each | cut -d/ -f3  > $DRIVETEMP/mountpoint"$COUNTER"
              echo $NOTIFY > $DRIVETEMP/existing"$COUNTER" 
          else
              echo $each | cut -d/ -f3  > $DRIVETEMP/mountpoint"$COUNTER" 
              touch $DRIVETEMP/existing"$COUNTER" # Or cat gets upset  
	  fi
	done
    fi

head-col

    echo -e "\n  Note: Access is only with permissions level of user \"$USER\".\n"
info-col
    echo -e "  To detach a file system, access it and choose the \"unmount\" option.\n"	

    if [ $COUNTER -gt 9 ] ; then    
        echo -e "  As you have more than 9 devices, type your choice, then press <enter>...\n"	
    fi

head-col

    echo "  m: Return to the inx main menu."
    echo "  s: Go to the SSHFS Secure Access menu"
    echo "  u: Go to the USB menu"
    echo "  x: Give me a command prompt."
    echo

show_mounts 

f-ttynum

info-col

checkmount () # See how we need to mount or access a device 
{
    if ! grep $MOUNTDIR /etc/mtab > /dev/null 2>&1 ; then
        sudo mkdir -p $MOUNTDIR
        sudo mount $DEVICE $MOUNTDIR
    elif [ $DEVICE = "/" ] ; then
        MOUNTDIR="/"
    elif [ "$DEVICE" != "" ] ; then
        MOUNTDIR=$(grep $DEVICE /etc/mtab | tail -1 | awk '{print $2}')  
    else
        f-discmount # Don't do anything if $DEVICE doesn't exist.
    fi
    f-sup # Since the next move will start something...
}

if [ $COUNTER -gt 9 ] ; then
    read ACCESS
else
    read -s -n 1 ACCESS
fi

# Defaults - will be modified by "checkmount" in cases of previously mounted devices.
SUBDIR=$(cat $DRIVETEMP/mountpoint"$ACCESS" 2> /dev/null)
MOUNTDIR="/media/${SUBDIR}"
DEVICE=$(cat $DRIVETEMP/device"$ACCESS" 2> /dev/null)
EXISTING=$(cat $DRIVETEMP/existing"$ACCESS" 2> /dev/null)

case $ACCESS in

    m)
    cleanup
    f-menu
    ;;
    s)
    cleanup
    f-sshfs
    ;;
    u)
    cleanup
    f-usb
    ;;
    x)
    cleanup
    tput sgr0 ; clear
    f-prompt
    ;;
    [0-9] | [0-9][0-9]) 
    # Don't try to do anything with out of range, non-existent devices.
    if [ $ACCESS -gt $NUMBER_OF_DEVICES ] ; then
        echo -e "\n  Oops, \"$ACCESS\" doesn't seem to exist  - please try again..."
        sleep 3
        f-discmount
    fi	
    # OK, it might make sense... let's see.. 
    if [ "$DEVICE" = "/" ] ; then
        : # no-op
    elif grep $DEVICE /etc/mtab | awk '{print $2}' | grep /media/usb > /dev/null 2>&1 ; then 
        echo -e "\n  This appears to be a mounted USB device - taking you to the USB menu..."
        sleep 3
        cleanup
        f-usb
    elif ! [ -f $DRIVETEMP/mountpoint"$ACCESS" ] ; then
        echo -e "\n  Oops.. that doesn't seem to be an option..."
        sleep 2
        f-discmount
    fi	
    ;;
    *)
    f-discmount
    ;;
esac

part2 ()
{	
unbold ; clear  
fig-col
figlet "  drive access"

if [ "$EXISTING" ] ; then
  MOUNTDIR=$EXISTING
fi
	
head-col
      
echo -e "\n  Select your preference for $MOUNTDIR:" 
info-col

cat << EOMOUNTPREFS

  1: Midnight Commander  (mc)  
  2: Vifm                (vifm)
  3: Linm                (linm)
  4: Moc Music Player    (mocp)
  5: Command Line              

EOMOUNTPREFS

head-col
echo "  m: Return to the  INX Main Menu."
echo "  d: Return to the hard drive menu."
echo "  u: Unmount / Detach $MOUNTDIR"
echo "  x: Give me a prompt."
echo 

show_mounts

f-ttynum

# partition choices: choices and opening in e.g. mc , vifm etc.
# No sudo for access - too risky :)
# "Checkmount" mounts unmounted devices.

    read -s -n 1 WHATSNEXT
    case $WHATSNEXT in
    1)
    checkmount
    mc $MOUNTDIR
    part2
    ;;
    2)
    checkmount
    cd $MOUNTDIR && vifm && cd
    part2
    ;;
    3)
    checkmount
    cd $MOUNTDIR && linm && cd
    part2
    ;;
    4)
    checkmount
    mocp $MOUNTDIR
    pkill mocp # moc likes to hang on to its working directory...
    part2
    ;;
    5)
    checkmount
    clear ; head-col
    echo -e "\n  OK - giving you a prompt at the mountpoint..." 
    echo -e "  This is a subshell: remember to exit when done.\n"
    cd $MOUNTDIR
    tput sgr0
    /bin/bash
    cd # The script needs to get out of $MOUNTDIR or it will show "busy"
    part2
    ;;
    u)
    if grep $MOUNTDIR /etc/mtab > /dev/null 2>&1 ; then
        if sudo umount $MOUNTDIR 2> $DRIVETEMP/umount-error ; then
            yellow
            echo -e "\n  OK - unmounting $MOUNTDIR..."
            sleep 3
            f-discmount
        else
            echo -e "\n  Could not unmount $MOUNTDIR - umount says:\n"
            EUMOUNT=$(cat $DRIVETEMP/umount-error)
            printf "  " ; echo $EUMOUNT ; EUMOUNT=  #indentation kludge
            sleep 5 ; clear
            part2
        fi
    else
        echo -e "\n  $MOUNTDIR is not mounted, according to mtab."
        sleep 3 ; clear
        part2
    fi	
	
    ;;
    d)
    f-discmount
    ;;
    x)
    cleanup
    f-prompt
    ;;
    m)
    cleanup
    f-menu
    ;;
    *)
    part2
    ;;
esac
}

part2
}

# Menu to select usb or hard drive option, or sshfs

f-drivinx ()
{

unbold ; clear 
fig-col
figlet "  File Systems"
head-col
echo -e "\n  Attach and detach file systems."
info-col
echo
echo "  1: Usb Devices"
echo "  2: Hard Drive Partitions"
echo "  3: Network Share Files"
echo
head-col
echo "  m: Return to the main inx menu"
echo "  u: Unmount / Detach File Systems."
echo "  x: Give me a command prompt"

show_mounts

f-ttynum

read -s -n 1 DRIVE
    case $DRIVE in
        1)
	f-usb
	;;
	2)
	f-discmount
	;;
	3)
	f-sshfs
	;;
	m)
	f-menu
	;;
	u)
	echo -e "\n  Choose the type of file system to detach, then follow the menu instructions.\n"
	sleep 4
	f-drivinx
	;;
	x)
	f-prompt
	;;
	*)
	f-drivinx
	;;
    esac
}    
