#!/bin/sh

PATH=/bin:/usr/bin:/usr/local/bin
tmp=/tmp/websh$$
trap "rm -f $tmp" 0 1 2 15
rm -f $tmp

case $# in
0)
    url=
    echo no URL specified yet, use \'c\' >$tmp
    ;;
1)
    url="$1"
    lynx -source -dump -base "$url" >$tmp
    ;;
*)
    echo usage: $0 \[url] >&2
    exit 1
    ;;
esac


while true
do
    echo -n 'Command (? for help): '
    read cmd arg || exit 0
    case "$cmd" in
    c)
	url="$arg"
	lynx -source -dump -base "$url" >$tmp
	;;
    g)
	newurl="`lynx -dump -force_html $tmp | grep ' '$arg'\.' | tail -1 | sed 's/^ *'$arg'\. *//'`"
	if test -z "$newurl"
	then
	    echo no such reference >&2
	else
	    url="$newurl"
	    lynx -source -dump -base "$url" >$tmp
	fi
	;;
    s)
	lynx -dump -force_html $tmp | more
	;;
    b)
    	echo "$url" >>$HOME/bookmarks
	;;
    B)
	(echo '<pre>'; cat -n $HOME/bookmarks | sed 's/\([0-9]\)	/\1. /') >$tmp
	lynx -dump -force_html $tmp | more
	;;
    i)
	tr -s ' \011\012"' \\012 <"$arg" | grep \^http:// | \
		sed 's/[.,;]$//' >>$HOME/bookmarks
	;;
    \?)
	cat <<\EOF
Type one of:
c URL - change URL
g # - go to reference #
s - show current web page
b - bookmark current web page
B - show bookmarks; then select with 'g'
i file - import bookmarks from free-format file
EOF
	;;
    q)
	break
	;;
    ?*)
	echo "'?' for help"
	;;
    esac
done
