#!/bin/sh
# by fenn (aka ben lipkowitz) distributed under GPL v2 or later
#
# opens a new konqueror browser window without starting a new process;
# this is about six times faster than running a new instance.
#
# usage:
# newkonq.sh [-b | url]
# if given -b it uses the contents of the x selection buffer 
# if given a url it goes there, else it googles the phrase
#
# installation:
# do chmod a+x newkonq.sh and then put this script in /usr/local/bin 
# now get "xsel" (sudo apt-get install xsel)
#
# for added functionality:
# if you use IceWM, add this to your ~/.icewm/keys file:
# key "Alt+Ctrl+l"                newkonq.sh -b
# now highlight something and press control-alt-L and see what happens!
# (it should google the selected text)
# other window managers (gnome, KDE) should have custom keyboard 
# shortcuts too, but i'm too lazy to look up how to do that!
# ---------------------------------------------------------------------

home_page="http://www.google.com/"

# opens a new window at the url in the first konqueror process found.
# if there isnt one running yet, start one first.
new_window () {
  if (ps -e | grep -q konqueror)
    then
      dcop $(dcop konq* | head -1) KonquerorIface createNewWindow "$*"
    else 
      konqueror &
      dcop $(dcop konq* | head -1) KonquerorIface createNewWindow "$*"
  fi
}

#match url's that dont begin with http://
informal_url_pattern=".*\.(com|org|gov|net|edu|new|info|au|ca|us|br|ro|at|de|uk|jp).*" 

my_args="$*"

if ( echo "$1" | grep -q "-b" - )
then 
  echo "using contents of selection buffer"
  string="`xsel`"
  echo $string
  if (echo "$string" | grep -qE "^ *http(s)?|ftp|fish|file://.*" - )
    then echo "url found: $string"; new_window $string  
  elif [[ $string == "" ]]
    then new_window $home_page; echo "empty buffer"
  elif ( echo "$string" | grep -qE  $informal_url_pattern - )
    then echo "informal url found: $string"; new_window $string 
  else
    quote='%22'
    url="http://www.google.com/search?q=$quote$string$quote"
    new_window $url 
    echo "using google: $url"
  fi
else
  new_window "$my_args"
fi

