#!/bin/bash
PATH=$PATH:/usr/local/lib/inx
. inx_essentials
maybe_switch

#######################################
# 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
    exec menu
    ;;
    s)
    cleanup
    exec sharinx
    ;;
    u)
    cleanup
    exec 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
        exec 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
    exec menu
    ;;
    *)
    part2
    ;;
esac
}

part2
}

f-discmount