#!/bin/bash
# 
# mgt-helper, included with Multi Gnome Terminal 
#
# $Id: mgt-helper,v 1.20 2002/08/27 01:26:35 hal9 Exp $
# 
# Purpose: A shell script to use with Multi Gnome Terminal that adds
#          additional functionality at the shell level. 
#
#          There are two types of functionality included here:
#
#          a) Features that are best done in the shell environment, 
#             and would be difficult to do otherwise (eg the history,
#             debug, and URL handler options) so as to extend MGT.
#
#          b) Features that users might find useful, but could certainly 
#             be done through other means. These are included just as 
#             an aid for those who want a quick and easy implementation.
#             And possibly as a way of eliciting better ideas.
#
# Usage: mgt-helper [option] CMD_OPTION [arguments to CMD_OPTION]
#
# License: GPL, see LICENSE file.
#
# Copyright (c) 2002 Cristiano De Michele, Hal Burgiss
#
#
# BUGS: 
#       -Not ready for prime time due to lack of testing.
#       -History option probably only works with bash.
#       -pwd option is borked, and may be fatally flawed. Disabled.
#       -Completely untested on shells other than bash.
#       -Some features only work on Linux (probably), notably the 
#        URL Handlers.
#
# NOTE: 
#       This script includes a collection of essentially independent
#       subroutines for the sake of convenience. They are not meant to be used
#       in conjunction with each other, and probably will not work if this is
#       tried. Use one option at a time.
#
#       The FILE_HANDLER stuff is crude, and probably needs work.
#
# WARNING: This script is not well tested yet, and should be considered
#          alpha quality.
#
# If you have improvements or suggestions for this script, please mail to:
#
#   multignometerm-devel@lists.sourceforge.net
#
#######################################################################

# This script automatically looks first for a /etc/mgt-helper.rc and a
# ${HOME}/.mgt-helper.rc file for user defined preferences. Only set RC_FILE
# here if using something else. Set site preferences go in this file (will
# need to be created). The user's .mgt-helper.rc takes precedence.
#RC_FILE=/usr/local/etc/mgt-helper.rc

########################################################################
# The following variables can be set in $RC_FILE, for user or site
# preferences. If the same variable is defined in both places, $RC_FILE takes
# precedence, and $HOME/$RC_FILE the last word. It is strongly recommended to
# use an $RC_FILE, so you don't lose settings on upgrades.

# NOTE: URL Handlers only work on Linux at this time!

# Preferred MGT action for displaying URL Handlers, etc. eg --add-tab, or
# --add-window, --hsplit, etc. Used in other places too. Do not use 
# compound actions here. Do that with -XT command line over-ride.
#URL_ACTION="--add-window-wt --add-tab"
#URL_ACTION="--add-tab"
URL_ACTION="--hsplit"

# If URL_ACTION is hsplit, then this can be set to force a new Tab
# instead when the terminal window is less than this value high.
# This probably only works with URL Handlers on Linux, and only 
# if terminal parameters are avaiable (not always the case).
SPLIT_MIN_HT=30

# If URL_ACTION is vsplit, then this can be set to force a new Tab
# instead when the terminal window is less than this value wide.
# This probably only works with URL Handlers on Linux, and only 
# if terminal parameters are avaiable.
SPLIT_MIN_WIDTH=90

# The user's preferred text browser, like links or w3m. Used for 
# the google actions, and also HTTP URL Handler. Do NOT set this to 
# a GUI Browser like Mozilla or Netscape!!! If not defined, this 
# script will try to find an appropriate one.
#HTTP_HANDLER=
#HTTP_LABEL_NAME=WWW

# This will be used to handle HTTP URLS if MGT is not the calling 
# program.
GNOME_HTTP_HANDLER=gnome-moz-remote

# The preferred text ftp client. If not defined, the value of 
# HTTP_HANDLER will be used.
#FTP_HANDLER=ncftp
#FTP_LABEL_NAME=ncftp

# This will be used to handle FTP URLS if MGT is not the caller.
GNOME_FTP_HANDLER=gnome-moz-remote

# The preferred text file viewer and directory browser. If not defined, the
# default of mc (Midnight Commander) is tried. This will actually be launched
# as 'mc -v' for most regular files. Note: some file types are handled
# directly by $0.
#FILE_HANDLER="/usr/bin/mc -C 'base_color=normal=white,default:marked=magenta,default'"
FILE_HANDLER=mc
FILE_LABEL_NAME=$FILE_HANDLER

# Start up options for midnight commander. FIXME: testing.
MC_ARGS="-c -C base_color=normal=white,default:marked=magenta,default"

# Handlers for special file types:
# For images like png's and gif's. If not defined, this script tries 
# to find one.
#IMAGE_HANDLER=

# If you want to use a web browser rather than a file manager, set 
# it here, for file:/// urls that happen to be html and similar.
HTML_HANDLER=$HTTP_HANDLER

# pdftotext -htmlmeta $2 /tmp/_tmp.html && $HTTP_HANDLER /tmp/_tmp.html
#PDF_HANDLER=

#PS_HANDLER=

#SOUND_HANDLER=

#MIDI_HANDLER=

# This will be used to handle file viewing if MGT is not the calling 
# program.
GNOME_FILE_HANDLER=nautilus

# The preferred text mail client to compose mail. If not defined, 
# the GUI mail handler will be used (see below).
MAILTO_HANDLER="mutt"
#MAIL_LABEL_NAME="$MAILTO_HANDLER: NewMail"
MAIL_LABEL_NAME="To: $(echo $2| sed -e 's,mailto:,,' |sed -e 's,@.*$,,')"

# This will be used to compose mail if MGT is not the caller, or 
# text mail client is not defined.
GNOME_MAILTO_HANDLER=evolution

# Command to pause the terminal after errors, or for debug option.
SLEEP_CMD="sleep 3"

# Preferred shell startup command, used now for history option only.
SHELL_CMD="bash --login"

# Default history file for $SHELL_CMD. Only change this if not using bash, 
# or you are doing something really unusual, and know WTF you are doing.
# Actually, doubtful the user defined history file feature works with anything
# except bash at this point.
HIST_FILE="${HOME}/.bash_history"

# Only set this if MGT is not finding the correct ssh version in your path, 
# or you want to add other options to the command line. mgt-helper simply 
# executes 'mgt-helper -s' as just 'ssh'. 
SSH_CMD=ssh

# Command to run when su'ing from mgt-helper (so as not to kill URL 
# handling).
SU_CMD="su -"

# Set this only if MGT is not in your PATH, or you want to use a MGT version 
# other than the one first in your PATH.
#MGT=

# By default, for the User Guide installation directory, this script 
# tries /usr/share/gnome/help/multi-gnome-terminal/C/index.html and 
# the same in /usr/local. Set this to another PATH only if the script 
# doesn't find the version you want. This will be the default in that 
# case then.
#UG_PATH=

# ls -F appends special characters to the filename to denote file type.
# These get in the way of URL Handlers. If set to non-empty value, these are
# stripped from the end of *any* file name. Also, a colon ':' is stripped.
# Defaults to on.
STRIP_LS_F=ofcourse

# If the 'dict' program is installed, and this is set to *anything* at all,
# dict will be used for word lookup. Else, the Merriam Webster online
# dictionary is used.
PREFER_DICT=whynot

# FIXME. Not used.
GOOGLE_LANG=

# FIXME. Not used.
GOOGLE_HITS=

#######################################################################
# Do not edit below this point. #######################################

# These can also be set in ${HOME}/.mgt-helper.rc, if wanted, which 
# is automatically checked for and does not need to be defined here.
WHOAMI=`basename $0`
PTS_FILE=${HOME}/.mgt_tty
APP_NAME=multi-gnome-terminal
MGT=${MGT:-"`which multi-gnome-terminal`"}
shopt -s execfail

# For testing and debugging purposes only.
#DEBUG=on
DEBUG_FILE=/tmp/$WHOAMI.debug
#TESTING=makeitso

## Function Declarations ##############################################

debug () {
 [ -n "$DEBUG" ] && return 0 || return 1
}

testing () {
 [ -n "$TESTING" ] && return 0 || return 1
}

# Usage function.
usage() {
 echo -e \\nusage: "mgt-helper [option] CMD_OPTION [cmd args]\\n
 General Options, may be combined:\\n
   -D, turn on \"verbose\" mode.

   -r  RC_FILE, specify a config file, whose settings will over-ride 
       other config file settings.

   -T, force the action to a full Tab.

   -H, force the action to a horizontal split Tab.

   -V, force the action to a vertically split Tab.

   -W, force the action to a New Window.

   -WT, force the action to a New Window with startup Tabs for this Class.

   -A, force this action to be used by CMD_OPTION below, e.g. 
        \"--add-tab --tclass myclass\".
 
 CMD_OPTIONs are one, and only one, of the following:\\n
  -h | --history EXTENSION, force a user defined, custom history file for
         this term, where EXTENSION is a user-defined, unique string.
         This probably only works with bash right now. Use with Edit Commands.

  -u | --url-handler | http-handler, for use as GNOME HTTP URL Handler.
         Set up in GNOME. This opens a new Tab with a text browser.
         Example from ~/.gnome/Gnome: http-show=mgt-helper -u \"%s\"
         All URL Handlers only work on Linux at this time.

  -f | --ftp-handler, for use as GNOME FTP URL Handler. Set up in 
         GNOME. This opens a new Tab with a text ftp client.

  -m | --mailto-handler, for use as GNOME mailto URL Handler. Set up in
         GNOME. This opens a new Tab with a text mail client. Default is
         mutt.

  -F | --file-handler, for use as GNOME file URL/Document Handler. Set 
         up in GNOME. This opens a new Tab with a file viewer. Default
         is Midnight Commander (mc). A few special file types are 
         handled separately, eg images.

  -x | --execute COMMAND[, COMMAND...], use to execute compound shell 
         commands from Edit Commands (e.g. 'echo hello world ; ps |
         less ; echo bye now && read' will work). Use with Edit Commands
         or with $APP_NAME's '-x' command line option.

  -U | --user-guide, open User Guide in Tab. Use with Edit Commands,
         or run from shell prompt.

  -s | --ssh [ssh options] HOST [commands], use mgt-helper as a ssh wrapper. 
         This is probably only useful where the sshd daemon may be running as
         another user, and thus breaks our GNOME URL Handling tricks. Use with
         Edit Commands, if needed (ie URL Handlers don't work).

  -S | --su, su can also break URL Handling tricks. Use this instead of 
         the MGT menus/shortcuts. Edit Commands.
  
  -g | --google, search Google. Use with Edit Commands.

 -lg | --lin-google, search Google/Linux only. Use with Edit Commands.
 
  -l | --lookup [word], Look up a word in on-line dictionary. Use with 
         Edit Commands, or from shell prompt.

  -d | --debug CMD_TO_DEBUG [args], a troubleshooting aid to capture
         error output from shell commands (NOT MGT internals) that might
         vanish quickly otherwise. Use with Edit Commands.

  --show-all, this just dumps all variables from the bash environment to
         STDOUT and writes the same data to /tmp/mgt-helper.debug. For
         troubleshooting only.

  Read the comments in the script for additional information and 
  variables that may be set to user preferences. Use only one option
  at a time.

$WHOAMI is distributed with Multi Gnome Terminal, and is Copyright (c)
2002 Cristiano De Michele, Hal Burgiss, and licensed under the GPL.
"
 exit 0
#  -p | --pwd [-h|-v], open a new Term using the present directory for PATH.
#           -v and -h force a split terminal, otherwise a new Tab
#           is created. FIXME: DO NOT USE! DOES NOT WORK!
#

}

# Function to make pseudo-intelligent choice for a text browser.
get_tbrowser() {
 
 # allow for override in script headers or $RC_FILE.
 debug && echo Default HTTP_HANDLER: "$HTTP_HANDLER" |tee -a $DEBUG_FILE
 [ -n "$HTTP_HANDLER" ] && return 0
 
 # Try to find something useful in environment or $PATH.
 if ! echo $BROWSER | grep "\blinks\|w3m\|lynx\b" >/dev/null; then 
    for i in w3m links lynx; do
      if which $i >/dev/null 2>&1; then
        HTTP_HANDLER=$i
        HTTP_LABEL_NAME=${HTTP_LABEL_NAME:-"$i"}
        break
      fi
    done
 
    [ -z "HTTP_HANDLER" ] && die "No text browser found, exiting."
    debug && echo Text Browser found: $HTTP_HANDLER |tee -a $DEBUG_FILE
 
 else
 # user was smart, and had a sane default. Let's use that.
  HTTP_HANDLER=$BROWSER
  HTTP_LABEL_NAME=${HTTP_LABEL_NAME:-"$BROWSER"}
 fi

}

# Generic error message function.
err_msg () {
 local my_sleep=$SLEEP_CMD
 
 [ "$1" = "-r" ] && my_sleep=read && shift
 printf "\n     $WHOAMI: $*\n\n" ; $my_sleep
 return 0

}

# Fatal error
die () {
 err_msg $* ; exit 1
}

# Handle URLs here. Only for use with 'GNOME URL/document Handlers'!
url_handler () {
 debug && echo "Handler ARGs:  1:$1 2:$2 3:$3 4:$4 pts: `cat $PTS_FILE`" |tee -a $DEBUG_FILE
 url="$2"
 if echo $url |grep "^ghelp:" >/dev/null ;then
  url=$(echo $url | sed -e 's@ghelp:@file://@')
  debug && echo ghelp kludge: $url
 fi
 # Use the gnome handler here if PTS_FILE is not found.
 [ -f $PTS_FILE ] || exec $3 $url
 TTY=`cat $PTS_FILE`
 rm -f $PTS_FILE
 [ -n "$4" ] && TNAME="--tname=$4"
 exec $MGT --nowait $URL_ACTION "$TNAME" -x $1  $url > $TTY 
}

# See if we are called from MGT/Edit Commands or not. This makes a 
# difference, ie MGT will open tabs/terms for us from Edit Commands,
# otherwise we have to do it ourselves. Probably also only works with
# bash.
is_mgt_parent () {
 /bin/ps x |grep $PPID | grep $APP_NAME >/dev/null && return 0
 debug && echo PPID: $PPID |tee -a $DEBUG_FILE
 return 1
}


# Function to see if FILE_HANDLER is dealing with a non-regular file.
check_ftype() {
 local stat_file

 # FIXME. Check for man/info pages.
 
 # Check we have a valid file. FIXME: does not handle wildcard chars.
 #ls $file >/dev/null 2>&1 || exit 1
 [ -e "$file" ] || exit 1
 
 # check for script
 [ -x "$file" ] && file "$file" |grep script >/dev/null && return 0
 
 # let file viewers handle regular files and directories.
## ! [ -x "$file" ] && return 0
 [ -f "$file" -o -d "$file" ] && ! file $file | grep ELF >/dev/null && return 0
 # FIXME: The above is a bit of a kludge and probably needs refinements.

 # see if we have 'stat'.
 which stat >/dev/null 2>&1 && stat_file="$(which stat) $file"
 
 make_tempfile

 ( printf "#!/bin/sh\necho\necho\necho \"File Type for  \`file $file\`\"\n $stat_file\necho\necho -en '\t'Press Enter to Continue ...\nread" ) > $tmpscript

 # Otherwise, we handle special file types ourselves, e.g. device files.
 exec $MGT --nowait $URL_ACTION --tname $file -x  $tmpscript  > `cat $PTS_FILE`

}

# Function to launch midnight commander. FIXME, just testing stuff.
_mc () {    
 MC=$(which mc)
 debug && echo MC: $MC $MC_ARGS "$@"
 $MC $MC_ARGS "$@"
 #[ -n "$MC" ] && exec $MC $MC_ARGS "$@" || exit 1
}

# make a temp file, usually to build a script.
make_tempfile() {
 tmpscript=`mktemp /tmp/.$WHOAMI.XXXXXX` && chmod +x $tmpscript || exit 1
 debug && echo tmp_script: $tmpscript
}

### end functions #################################################

# Look for, and read in config files, and let them take precedence.
[ -r /etc/mgt-helper.rc ] && . /etc/mgt-helper.rc
[ -n "$RC_FILE" ] && [ -r $RC_FILE ] && . $RC_FILE
# Let User's home have last word.
[ -r ${HOME}/.mgt-helper.rc ] && . ${HOME}/.mgt-helper.rc

debug && echo $WHOAMI: debug is set && echo MGT: $MGT && echo Action: $URL_ACTION

# error testing since this would kill mgt if wrong ...
case $URL_ACTION in
  --add-tab|--hsplit|--vsplit|--add-window*|--newapp*)
    # do nothing
    :
  ;;
  *)
    URL_ACTION="--add-tab"
  ;;
esac


# FIXME: First check for general options: -D, -r. These must 
# come BEFORE any Command Options! Not well tested.

for i in $*; do
     case $1 in
       -D)
         # bash specific. Turn on verbose/debug messages from command line.
         shift
         DEBUG=turnmeon
         debug && echo DEBUG set via command line.
       ;;
       -r)
         # Set a different rc file for this run. This will override 
         # config in other files which are parsed beforehand.
         shift
         [ -r $1 ] && . "$1"
         debug && echo "rcfile: $1 is overriding."
         [ -r $1 ] && shift
       ;;
       -T)
         # Force URL_ACTION to full Tab.
         shift
         URL_ACTION="--add-tab"
       ;;
       -H)
         # Force URL_ACTION to hsplit.
         shift
         URL_ACTION="--hsplit"
       ;;
       -V)
         # Force URL_ACTION to hsplit.
         shift
         URL_ACTION="--vsplit"
       ;;
       -W)
         # Force URL_ACTION to New window.
         shift
         URL_ACTION="--add-window"
       ;;
       -WT)
         # Force URL_ACTION to New window with tabs.
         shift
         URL_ACTION="--add-window-wt"
       ;;
       -A)
         # User defined URL_ACTION, which can be compound.
         shift
         URL_ACTION="$1"
         shift
       ;;
     esac
done


# Set to full Tab if we are below our preferred minimum terminal size values.
# Note stty is not available in all situations.

[ -f $PTS_FILE ] &&\
if [ "$URL_ACTION" = "--hsplit" ]; then
     if [ -n "$SPLIT_MIN_HT" ] &&\
        [ $(stty -F `cat $PTS_FILE` size | awk '{print $1}') -lt $SPLIT_MIN_HT ]
         then
         URL_ACTION="--add-tab"
     fi
elif [ "$URL_ACTION" = "--vsplit" ]; then
     if [ -n "$SPLIT_MIN_WIDTH" ] &&\
        [ $(stty -F `cat $PTS_FILE` size | awk '{print $2}') -lt $SPLIT_MIN_WIDTH ]
         then
         URL_ACTION="--add-tab"
     fi
fi

debug && echo CMD_OPTIONS: $* && echo  Final Action: $URL_ACTION

# Write environment, ect to file.
debug && set > $DEBUG_FILE &&\
 echo $WHOAMI Command line: "$*" >> $DEBUG_FILE

#######################################################################
## begin parsing command line, and doing something useful.

# strip any leading hyphens from first arg, which are optional, despite 
# what usage says :)
args=`echo "$1" | sed -e 's@^-\?-@@'`

case $args in

  # Execute complex, compound shell commands.
  x|execute)
   shift
   debug && echo Incoming exec args: $*
   eval $*
   #exit
   #make_tempfile
   #printf "#!/bin/sh\n\$\*\n" > $tmpscript
   #$tmpscript && rm -f $tmpscript
  ;;

  # ssh helper so that URL handlers work where sshd is running as 
  # another user, and interfering with our neat little tricks.
  s|ssh)
   shift
   debug && echo "ssh command: $SSH_CMD $*" |tee -a $DEBUG_FILE
   ## NO EXEC! Exec breaks URL handling.
   $SSH_CMD $*
  ;;

  # su from here to overcome problems with URL Handling if done just 
  # from MGT menu/shortcuts.
  S|su)
   $SU_CMD
  ;;

  # Open user guide in a Tab, use either from shell or Edit Commands.
  U|user-guide)
   get_tbrowser
   for i in $UG_PATH \
            /usr/share/gnome/help/multi-gnome-terminal/C/index.html \
            /usr/local/share/gnome/help/multi-gnome-terminal/C/index.html ; do
     [ -f $i ] && ug=$i && break         
   done
   if is_mgt_parent; then
     $HTTP_HANDLER $ug
   else
     exec $MGT $URL_ACTION --tname="User Guide" -x $HTTP_HANDLER $ug 
   fi
  ;;
  
  # URL Handlers ######################################################
  # For use as GNOME HTTP URL Handler.
  u|url-handler|http-handler)
   get_tbrowser
   url_handler "$HTTP_HANDLER" "$2" "$GNOME_HTTP_HANDLER" "$HTTP_LABEL_NAME"
  ;;

  # For use as GNOME FTP URL Handler.
  f|ftp-handler)
   [ -z "$FTP_HANDLER" ] && get_tbrowser && FTP_HANDLER=$HTTP_HANDLER
   url_handler "$FTP_HANDLER" "$2" "$GNOME_FTP_HANDLER" \
      "${FTP_LABEL_NAME:-$HTTP_LABEL_NAME}"
  ;;

  # For use as GNOME mailto client.
  m|mailto-handler)
   mailto="$2"
   if [ -z "$MAILTO_HANDLER" ]; then
   # Use GUI handler, if text is not defined.
     $MAILTO_HANDLER="$GNOME_MAILTO_HANDLER"
   else
   # strip 'mailto' that gnome, or somebody, puts in there.
     mailto=`echo "$2" | sed -e 's@mailto:@@'`
   fi 
   url_handler "$MAILTO_HANDLER" "$mailto" "$GNOME_MAILTO_HANDLER" \
     "$MAIL_LABEL_NAME"
  ;;

  # For use as GNOME File Viewer.
  F|file-handler)
   debug && echo "Raw file arg: $2" |tee -a $DEBUG_FILE
   file="$2"
   
   # Compensate for 'ls -F'. Do this first to make sure '*' is 
   # not expanded. 07/07/02, add colon to the list.
   [ -n "$STRIP_LS_F" ] && file=`echo $2 |sed -e 's,\(=\|@\|*\|\\\||\|:\)$,,'`
   
   file=`echo $file |sed -e 's@file://@@'`
   debug && echo '$file:'" $file" |tee -a $DEBUG_FILE

   # See what kind of file we are dealing with. Regular files and 
   # directories are handled below. Special files are handled by
   # the check_ftype function.
   check_ftype

   # Special cases... 
   # Image viewer
   case $file in
     *.png|*.jpg|*.jpeg|*.jpe|*.gif|*.xpm|*.tif|*.tiff)
      if [ -z "$IMAGE_HANDLER" ]; then
      # Try to find something useful for an image viewer
        for i in xv eog ee; do
         if which $i >/dev/null 2>&1; then
           IMAGE_HANDLER=$i
           FILE_LABEL_NAME="$i"
           break
         fi
       done
       
       [ -z "$IMAGE_HANDLER" ] && IMAGE_HANDLER=$FILE_HANDLER
       [ -z "$IMAGE_HANDLER" ] && die "Can't find a File Handler, exit." && exit 1
      
      fi
      
     debug && echo Image handler: $IMAGE_HANDLER |tee -a $DEBUG_FILE
     exec $IMAGE_HANDLER $file
     ;;
   esac

   [ -n "$HTML_HANDLER" ] &&\
   case $file in
     *.html|*.htm|*.shtml)
     debug && echo HTML handler: $HTML_HANDLER
     FILE_LABEL_NAME=$HTML_HANDLER
     FILE_HANDLER=$HTML_HANDLER
     ;;
   esac

   [ -n "$PDF_HANDLER" ] &&\
   case $file in
     *.pdf)
     exec $PDF_HANDLER $file
     ;;
   esac

   [ -n "$PS_HANDLER" ] &&\
   case $file in
     *.ps)
     exec $PS_HANDLER $file
     ;;
   esac

#    [ -n "$SOUND_HANDLER" ] &&\
#    case $file in
#      *.mid|*.midi)
#      exec $MIDI_HANDLER $file
#      ;;
#      *.wav)
#      exec $SOUND_HANDLER $file
#      ;;
#    esac
   
   [ "$FILE_HANDLER" = "mc" ] && FILE_HANDLER="$FILE_HANDLER $MC_ARGS"
   # If it is not a directory, try to view file contents...
   ! [ -d "$file" ] && FILE_HANDLER="$FILE_HANDLER -v"
   
   # Launch file handler, if nothing else matched above.
   url_handler "$FILE_HANDLER" "$file" "$GNOME_FILE_HANDLER" "$FILE_LABEL_NAME"
  
  ;;

  # This option gives a user defined bash history file for this terminal.
  # The command line argument becomes the unique extension. Use with 
  # Edit Commands only.
  h|history)
   # Give helpful error message if missing second argument.
   [ -z "$2" ] && die Second argument is required, aborting.
   # Good to go now. Probably only works with bash.
   export HISTFILE=$HIST_FILE-"$2"

   # if hist file is empty, use std bash_history as starting point so it is not
   # blank.
   ! [ -s $HISTFILE ] && cp -f $HIST_FILE $HISTFILE &&\
    echo $WHOAMI: creating custom history file

   # Start the preferred shell with user defined history file.
   exec $SHELL_CMD
  ;;

  # Open a new term in the current directory. Additional mgt ##########
  # args can be included. FIXME: This does not work, and maybe can't!!!
  pwd)
   testing || usage
   pwd && read
   cd `pwd` && bash
  ;;

  p|pwdx)
   testing || usage
   shift
   if [ "$1" = "-h" ]; then
     shift
     exec multi-gnome-terminal --hsplit --tpath=`pwd` "$*"
   elif [ "$1" = "-v" ]; then
     shift
     exec multi-gnome-terminal --vsplit --tpath=`pwd` "$*"
   fi
   exec multi-gnome-terminal --add-tab --tpath=`pwd` "$*" 
  ;;

  # search on google.com. #############################################
  g|google)
   get_tbrowser
   read -e -p "search google for: " google
   [ -z "$google" ] && exit 0 || clear
   $HTTP_HANDLER \
   "http://www.google.com/search?hl=en&q=%22$google%22&btnG=Google+Search"
  ;;

  # search only on google.com/linux. ##################################
  # FIXME: There is not a good reason that these two google searches 
  # could not be handled by one case statement.
  lg|lin-google)
   get_tbrowser
   read -e -p "search google.com/linux for: " lgoogle
   [ -z "$lgoogle" ] && exit 0 || clear
   $HTTP_HANDLER \
   "http://www.google.com/linux?num=50&restrict=linux&\
   hl=en&lr=lang_en&q=%22$lgoogle%22&btnG=Google+Search"
  ;;

  # Look up word in on-line dictionary or with 'dict', either from 
  # shell or Edit Commands.
  l|lookup)
   clear ; echo
   [ -z "$2" ] && read -e -p "  word to look up: " word || word="$2"
   [ -z "$word" ] && exit || clear
   
   export LESS="-P dict\:  Line %lb/%L   q to return  "
   # See if user prefers, and has, the 'dict' program/
   [ -n "$PREFER_DICT" ] && which dict >/dev/null 2>&1 &&\
   if is_mgt_parent; then
     dict "$word" | less +Gg
     exit $?
   else
     make_tempfile
     ( printf "#!/bin/sh\ndict \"$word\" | less\n" ) > $tmpscript
     exec $MGT $URL_ACTION --tname="dict: $word" -x $tmpscript 2>/dev/null || exit 1
   fi
   
   # else we use merriam webster on-line dictionay.
   get_tbrowser
   if is_mgt_parent; then
     $HTTP_HANDLER "http://www.m-w.com/cgi-bin/dictionary?book=Dictionary&va=$(echo $word | sed 's/ /+/')"
   else
     exec $MGT $URL_ACTION --tname="Lookup" -x \
     $HTTP_HANDLER "http://www.m-w.com/cgi-bin/dictionary?book=Dictionary&va=$(echo $word | sed 's/ /+/')"
   fi
  ;;
  
  # This is only useful for troubleshooting Tab commands that error ###
  # out, and then close the Tab so fast the error is not readable.
  # Use with Edit Commands. Not intended for use with URL handlers.
  d|debug)
   shift
   debug && echo "Debug ARGs: $*"
   [ -z "$*" ] && die "doh, you need to include another argument, exiting."
   # Run the remainder of command line in the shell.
   $* 
   # Here we caught an error of some kind ... we wait longer on this so user 
   # can study output, and save environment.
   [ $? -ne 0 ] && set >/tmp/$WHOAMI.env &&\
     die -r \
     "A shell error occurred. Press ENTER to continue...\\n
      \t (Shell environment has been written to /tmp/$WHOAMI.env)"
   # and here not ...
   err_msg "Command completed successfully ..."
#   echo "WARNING: If you can read this, you really need a faster system ;-)"
  ;;

  show-all|showall)
   set | grep "^[^[:space:]].*=" |tee $DEBUG_FILE
  ;;

  X)
   cat ./README ; read
  ;;

  *)
   usage
  ;;

esac

exit $?

#--- eof mgt-helper
