#! /bin/sh

###########################################################################
## Function to exit with error message.
## First param is return code, remaining params are lines of error message.
#
Fail() {
   ExitCode=$1
   shift
   echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" >&2
   echo "$(basename "$0"): FATAL ERROR" >&2
   while [ $# -gt 0 ]; do
      echo "$1" >&2
      shift
   done
   sleep 2
   TidyUp
   exit $ExitCode
}

###########################################################################
## Function to check a list of desired tools are available.
#
Toolcheck() {
   while [ $# -gt 0 ]; do
      TOOL="$1"
      shift
      echo "Checking '$TOOL'"
      which "$TOOL" >/dev/null 2>/dev/null \
         || Fail 3 "'which' failed for '$TOOL' - can't find this command."
   done
} 

#///////////////////////////////////////////////////////////////
OpenLink () {
   SELF=$(basename $0)

   if [ "$SELF" = 'browse' -o "$SELF" = 'b' ]; then
      opera --nomail --newpage "$1" 2>/dev/null >/dev/null &
   else
      # Something is stopping iceweasel from loading the cmd-line URL
      # It might be to do with the environment, in that a simple
      # invocation of "iceweasel /etc/iceweasel/iceweaselrc" in this 
      # script doesn't work, but doing it from shell cmd-line does
      iceweasel -new-tab "$1" &
   fi
}

#///////////////////////////////////////////////////////////////
OpenAllOnClipboard () {
   STARTEDBROWSER=False
   for TARGET in $(xclip -o | tr ' !|<>,' '\n'); do
   #for TARGET in $(xclip -o); do
   #xclip -o | tr ' !|<>,' '\n' | while read -r TARGET; do
      # Choose anything that looks like it could be a url (contains
      # a '.' with at least one char on each side) or path (starts
      # with a '/' - only absolute paths are reasonable when opening
      # from clipboard - there is no sensible working dir)
      if [ \
        "${TARGET#*?.?}"  != "$TARGET" -o \
        "${TARGET#/*?/?}" != "$TARGET"    \
        ]; then
         # Don't open anything with an '@' in it, since it's probably an email address!
         if [ "${TARGET#*@}" = "$TARGET" ]; then
            OpenLink "$TARGET"
            STARTEDBROWSER=True
         else
            echo Probably email: "$TARGET"
         fi
      else
         echo not URL: "$TARGET"
      fi
   done
   if [ "$STARTEDBROWSER" != "True" ]; then
      echo No URL found, opening browser with nothing
      OpenLink
   fi
}
# old tests for specific things:
#        "${TARGET#http:}" = "$TARGET" -a \
#        "${TARGET#www.}"  = "$TARGET" -a \
#        "${TARGET#file:}" = "$TARGET" -a \
#        "${TARGET%.htm}"  = "$TARGET" -a \
#        "${TARGET%.html}" = "$TARGET"    \

#///////////////////////////////////////////////////////////////

Toolcheck \
   xclip  \
   opera

if [ "$#" = "0" ]; then
   OpenLink "$(pwd)"
elif [ "$1" = "CLIPBOARD" ]; then
   OpenAllOnClipboard
else
   for TARGET in "$@"; do
      OpenLink "$TARGET"
   done
fi

