#!/bin/sh
# $Id: surfraw.IN,v 1.17 2009-04-05 19:57:29 ianb-guest Exp $
# Surfraw -- Shell Users' Revolutionary Front Against the World wide web
#
#  Copyright (c) 2003-2009 The Surfraw-Devel Team
#                          <surfraw-devel@lists.alioth.debian.org>
#  Copyright (c) 2000-2001 Julian Assange, placed into the public domain
#  Copyright (c) 2000 Melbourne Institute for Advanced Study, placed into the public domain
#
# see the file COPYING for further copyright details
#

surfraw_version=2.2.5
surfraw_api_version=1.0
w3_argv0=`basename "$0"`

elvidir="/usr/local/lib/surfraw"

# defaults

w3_config_hook () {
    return 1
}

w3_config () {
	prefix=/usr/local
   def   SURFRAW_global_conf	/etc/surfraw.conf
   def   SURFRAW_conf		$HOME/.surfraw.conf

	test -r "$SURFRAW_global_conf" || err "couldn't source SURFRAW_global_conf ($SURFRAW_global_conf)"
    . "$SURFRAW_global_conf"
    w3_config_hook
    test -r "$SURFRAW_conf" && . "$SURFRAW_conf"
}

warn () {
    echo "$w3_argv0 WARNING: ""$@"
}

err () {
    echo "$w3_argv0 ERROR: ""$@"
    exit 1
}

yesno () {
    eval value=\$${1}
    case `echo "$value" | tr A-Z a-z` in
	yes|true|on|1)	return 0 ;;
	no|false|off|0)	return 1 ;;
	*) err "\"$1\" is not set correctly. Should be (yes|on|1|no|off|0). Is \"$value\"" ;;
    esac
}

ifyes () {
    yesno "$@" && return 0
    return 1
}

ifno () {
    yesno "$@" && return 1
    return 0
}

ok () {
    yesno "$@"
}

null () {
    test -z "$@" && return 0
    return 1
}

def () {
    eval value=\$${1}
    test -z "$value" || return 0
    eval ${1}="$2"
    return 0
}

defyn () {
    eval value=\$${1}
    test -z "$value" && eval ${1}="$2"
    yesno "$1"
}

setopt  () {
    eval value=\$${1}
    eval ${1}="$2"
}

setoptyn () {
    eval value=\$${1}
    eval ${1}="$2"
    yesno "$1"
}

quote_ifs () {
	 if [ -z "$1" ];   then return;  fi
     perl -e '$ifs=$ENV{IFS} || " "; $arg=shift;if($arg =~/[$ifs]/) { $arg="\"$arg\""; } print "$arg\n"; ' -- "$1"
}

bookmark_file_search () {
	search="$1"
	file="$2"
	if [ -f "$file" ]
	then
		nawk -v search="$search" '$1 ~ search { print $2; }'  $file
	fi
}

bookmark_lookup () {
	search="$1"
	lookup=`bookmark_file_search "$search" ~/.surfraw.bookmarks`
	if [ -z "$lookup" ]
	then
		lookup=`bookmark_file_search "$search" /etc/surfraw.bookmarks`
	fi
	if [ -n "$lookup" ]
	then
		echo "$lookup"
	fi
}

w3_find_prog () {
  prog="$1"
  old_ifs="${IFS:-\" \"}"
  IFS=":"
  path_ifs="$PATH"
  for dir in $path_ifs; do
    test -z "$dir" && dir=.
    if test -e "$dir/$prog"; then
	echo "$dir/$prog"
	IFS="$old_ifs"
	return 0
    fi
  done
  IFS="$old_ifs"
  return 1
}

w3_url_escape () {
    echo "$@" | sed 's/%/%25/g;
		     s/+/%2B/g;
#		     s/ /+/g;
		     s/ /%20/g;
		     s/(/%28/g;
		     s/)/%29/g;
		     s/"/%22/g;
		     s/#/%23/g;
		     s/\$/%24/g;
		     s/&/%26/g;
		     s/,/%2C/g;
#		     s/\./%2E/g;
		     sx/x%2Fx;
		     s/:/%3A/g;
		     s/;/%3B/g;
		     s/</%3C/g;
		     s/=/%3D/g;
		     s/>/%3E/g;
		     s/?/%3F/g;
		     s/@/%40/g;
		     s/\[/%5B/g;
		     s/\\/%74/g;
		     s/\]/%5D/g;
		     s/\^/%5E/g;
		     s/{/%7B/g;
		     s/|/%7C/g;
		     s/}/%7D/g;
		     s/~/%7E/g;
		     s/`/%60/g;
		   '"s/'/%27/g"
}

w3_url_of_arg () {
    if ok SURFRAW_quote_args; then
        args=\""$@"\"
    else
        args="$@"
    fi
    if ok SURFRAW_escape_url_args; then
     	w3_url_escape "$args"
    else
	    echo "$args"
    fi
}

true () {
    return 0
}

false () {
    return 1
}

w3_global_usage () {
# style: keep sorted
#-------------------------------------79 cols----------------------------------
    cat <<EOF
Global options:
  -browser=EXECUTABLE		Set browser
				Default: $SURFRAW_browser
  -elvi				List Surfraw mechanisms for conquering evil
  -escape-url-args=yes|no	Apply url escaping to arguments
				Default: $SURFRAW_escape_url_args
				Environment: SURFRAW_escape_url_args
  -g | -graphical		Get some windowed sin
  				Default: $SURFRAW_graphical
				Environment: SURFRAW_graphical
  -help				What you're reading now, dude
  -p | -print			Just print search URL, don't pass to browser
  -quiet=yes|no			I can't enjoy it with you talking all the time
				Default: $SURFRAW_quiet
				Environment: SURFRAW_quiet
  -new[=yes|no]			Start in a new window
				Default: $SURFRAW_new_window
				Environment: SURFRAW_new_window
  -t | -text			Back to the yellow brick road
  -q | -quote			Quote arguments with " characters
				Default: $SURFRAW_quote_args
				Environment: SURFRAW_quote_args
  -version			Display Surfraw version ($surfraw_version)
  --				End of options
Copyright:
  Copyright (c) 2003-2009 The Surfraw-Devel Team
                           <surfraw-devel@lists.alioth.debian.org>
  Copyright (c) 2000-2001 Julian Assange <proff@iq.org>
  Copyright (c) 2001 Australian Institute for Collaborative Research
  Copyright (c) 2000 Melbourne Institute for Advanced Study
EOF
}

w3_usage_hook () {
    echo "Usage: $w3_argv0 [options] [args...]"
    w3_global_usage
}

w3_bad_option () {
    err "bad option \"${opt}\". Try ${w3_argv0} -help for usage information"
}

w3_parse_option_hook () {
    return 1
}

w3_parse_option () {
    opt="$1"
    case "$opt" in
	    -*=*) optarg=`echo "$opt" | sed 's/[-_a-zA-Z0-9]*=//'`
    esac
    w3_parse_option_hook "$opt" "$optarg" && return 0
    case "$opt" in
	-browser=*)	    setopt   SURFRAW_browser		$optarg	;;
	-elvi)		    sed -n 's/^.*elvis: \(.*\)$/\1/p' $elvidir/*; exit 0            ;;
	-escape-url-args=*) setoptyn SURFRAW_escape_url_args	$optarg ;;
	-g | -graphical)    setoptyn SURFRAW_graphical		yes	;;
	-help | --help)     do_help=1					;;
	-quiet=*)	    setoptyn SURFRAW_quiet	    	$optarg ;;
	-q | -quote)	    setoptyn SURFRAW_quote_args	    	yes	;;
	-new)		    setoptyn SURFRAW_new_window		yes	;;
	-new=*)		    setoptyn SURFRAW_new_window		$optarg ;;
	-t | -text)	    unset DISPLAY
			    setoptyn SURFRAW_graphical 		no	;;
	-version)	    echo $surfraw_version; exit 0	    	;;
	-p | -print)        setoptyn SURFRAW_print  yes     		;;
	--)		    setoptyn SURFRAW_end_of_args yes 		;;
	-*)		    w3_bad_option "$opt"		    	;;
	*)		    return 1					;;
    esac
    return 0
}

w3_parse_args () {
    w3_args=
    def SURFRAW_browser none
    def SURFRAW_browser_args none
    defyn SURFRAW_quote_ifs yes
    defyn SURFRAW_end_of_args no
    do_help=0
    mode=unknown
    for arg in "$@"; do
	isarg=1
	if ifno SURFRAW_end_of_args
	then
	    w3_parse_option "$arg"
	    isarg=$?
	fi
        if [ $isarg -eq 1 ]
	then
	    if ok SURFRAW_quote_ifs
	    then
		arg=`quote_ifs "$arg"`
	    fi
	    w3_args="$w3_args $arg"
	fi
    done
    if test $SURFRAW_browser = none; then
	if ok SURFRAW_graphical && test -n "$DISPLAY"; then
		SURFRAW_browser=$SURFRAW_graphical_browser
		SURFRAW_browser_args=$SURFRAW_graphical_browser_args
		mode=graphical
	else
		SURFRAW_browser=$SURFRAW_text_browser
		SURFRAW_browser_args=$SURFRAW_text_browser_args
		mode=text
	fi
    fi
    if ok do_help; then
	w3_usage_hook
	exit 0
    fi
}

w3_browse_url () {
   if ok SURFRAW_new_screen && test -n "$STY" && test $mode = text; then
   	screen=yes
   else
   	screen=no
   fi
    if ok SURFRAW_print; then
		echo "$@"
    elif ok screen; then
	if test $SURFRAW_browser_args = "none"; then
		$SURFRAW_screen $SURFRAW_browser "$@"
	else
		$SURFRAW_screen $SURFRAW_browser $SURFRAW_browser_args "$@"
	fi
    else
	if ok SURFRAW_graphical_remote && test $mode = graphical; then
		if ok SURFRAW_new_window; then 
			newwin=", new-window"
		else
			newwin=""
		fi
		if test $SURFRAW_browser_args = "none"; then
			$SURFRAW_browser -remote "openURL($*$newwin)" 2>/dev/null || $SURFRAW_browser "$@" &
		else
			$SURFRAW_browser -remote "openURL($*$newwin)" 2>/dev/null || $SURFRAW_browser $SURFRAW_browser_args "$@" &
		fi
	else
		if test $SURFRAW_browser_args = "none"; then
				$SURFRAW_browser "$@"
		else
			$SURFRAW_browser $SURFRAW_browser_args "$@"
		 fi
	fi
		
    fi
#    ifno SURFRAW_quiet && echo "Thank you for supporting the Shell Users' Revolutionary Front Rage Against the Web"
}

quote () {
	quoted=`echo "$1"|sed "s/'/'\\\\\''/g"`
	echo "'$quoted'"
}

surfraw_usage() {
	cat <<EOF
Usage: $w3_argv0 [-help] [-elvi] elvis [elvioptions] [search terms]
       $w3_argv0 [options] bookmark
    If you wish to run the elvi directly, run "surfraw-update-path" to append
	$elvidir to your \$PATH in your shell's config files.
    See surfraw-update-path(1) for details
Options:
   -elvi  List elvi
   -help  This help
sr is an alias for surfraw
EOF
	w3_global_usage
}

if [ "$w3_argv0" = "surfraw" -o "$w3_argv0" = "sr" ]
then
	w3_config
	opts=""
	unquoted_opts=""
	elvi=""
	searchterms=""
	for arg in "$@"
	do
	  # if it is an option
	  if awk -v arg="$arg" 'BEGIN { if(arg ~ /^-/) { exit 0 } else { exit 1 } } ' 
	  then
		  # if option before elvi
		  if [ -z "$elvi" ]
		  then
			  case "$arg" in
				  -help*) surfraw_usage;         exit 0 ;;
				  -\?)    surfraw_usage;         exit 0 ;;
				  -elvi*)  w3_parse_option -elvi; exit 0 ;;
			  esac
		  fi
		  if  [ -z "$opts" ]
		  then
			  opts="`quote "$arg"`"
			  unquoted_opts="$arg"
		  else
			  opts="$opts `quote "$arg"`"
			  unquoted_opts="$unquoted_opts $arg"
		  fi
	  elif [ -z "$elvi" ]
	  then
		  elvi="$arg"
	  else
		  if [ -z "$searchterms" ]
		  then
			  searchterms="`quote "$arg"`"
		  else
			  searchterms="$searchterms `quote "$arg"`"
		  fi
	  fi
	done
	if [ -z "$elvi" ]
	then
		surfraw_usage
		exit 0
	else
		if [ -x "$elvidir/$elvi" ]
		then
 			sh -c "$elvidir/$elvi $opts $searchterms"
		else
			bookmark=`bookmark_lookup $elvi`
			if [ -n "$bookmark" ]
			then
				w3_parse_args $unquoted_opts
				w3_browse_url "$bookmark"
			else
				echo "`basename $0`: $elvi: No elvis or bookmark with that name"
				surfraw_usage
				exit 1
			fi
	   fi
	fi
fi
