#!/bin/ksh
#
# ident "@(#)bbstartbrowser.sh	1.8 01/06/08 SMI"
#
# Copyright (c) 2001 by Sun Microsystems, Inc.
# All rights reserved.
#                                  
# start netscape and watch its windows

. $BBROOT/etc/opt/SUNWbb/blackbox.rc
. $BBPATH/config/browser.rc


PATH=/bin:$BBPATH/bin:/usr/openwin/bin:. ; export PATH

NETSCAPE=$BBPATH/bin/bbnetscape

LOCK=$BBHOME/.netscape/lock

XAUTHORITY=$BBHOME/.Xauthority; export XAUTHORITY

WATCH_POLL_RATE=20
START_POLL_RATE=2
RETRY=30

mypid="notset"
nspid="notset"
sleepid="notset"
local=0
num_urls=0
num_exit=0

trap do_exit 15

exit_browser() { 

	xkeyevent $BBDISPLAY Netscape ALT-q 
	sleep 1
}

do_exit() {
    
    echo "bbstartbrowser: do_exit"
    (( num_exit+=1 ))
    if [ $nspid != "notset" -a $nspid != "waitlock" ]; then
	if [ $num_exit -gt 1 ]; then
		bbkillproc 9 $nspid $BROWSER 
	else
		exit_browser 
		bbkillproc 9 $nspid $BROWSER
	fi
	nspid="notset"
    fi
    if [ $sleepid != "notset" ]; then
	bbkillproc 15 $sleepid sleep
	sleepid="notset"
    fi
}

# 
# we could sleep directly, but in that case we don't know
# the process id of the sleep and the trap function can't 
# kill the sleep ( without to many assumptions ).
# Therefore we fork the sleep, remember the pid and wait 
# for it explicitly. The trap then can kill the sleep since 
# we know the pid!
do_sleep() {

    sleep $1 &
    sleepid=$!
    wait $sleepid
}

download_files() {

    #
    # if we run in kiosk mode, then clobber all state in the download
    # area and provide the right content
    #

    bbdownload $BBUSER $BROWSERSTATE
    res=$?
    if [ -x $BBPATH/bin/bbstartkiosk ]; then
	BBUPDNDIR=`bbfind_uuid_dir $BB_TOKEN`
        rm -f $BBUPDNDIR/webtop.browser
	res=0
    fi
    return $res
}

upload_files() {

    res=0
    if [ ! -x $BBPATH/bin/bbstartkiosk ]; then
    	bbupload $BBUSER $BROWSERSTATE
    	res=$?
    fi
    return $res
}

find_windows() {

	xwinguard $BBDISPLAY Netscape
	res=$?
	if [ $res != 0 ]; then
		echo "find_windows: webtop status is $res"
	fi
	return $res
}

set_lock() {

	hostname=`uname -n`
	ipaddr=`$BBPATH/bin/bbip $hostname`
	/bin/ln -s $ipaddr:$mypid $BBHOME/.netscape/lock
}

clean_up() {

	lockpid="notset"
	if [ $local = "0" -a -h $LOCK ]; then
        	lockpid=`ls -l $LOCK | awk '{ print $11 }' | cut -f2 -d':'`
		exit_browser
		bbkillproc 9 $lockpid $BROWSER
	fi	
	if [ $nspid != "notset" -a $nspid != $lockpid ]; then
		exit_browser
                bbkillproc 9 $nspid $BROWSER
        fi 
        rm -f $LOCK 
	nspid="notset"
	/usr/openwin/bin/xsetroot -display $BBDISPLAY -cursor_name left_ptr
}

#
# read urls from the download area, this was the state
# of the webtop on the last exit of the webtop, not exit
# of the browser
# $1 - file containing the last browser state
read_urls() {

        typeset -i i=0
        while read url geom; do
                if [ $? != 0 ]; then
                        break
                fi
                last_urls[$i]="$geom $url"
		echo "${last_urls[$i]}"
                let "i+=1"
        done < $1
        num_urls=$i
}

# translate the geometry data into javascript function calls
# to rezise and move the given window  
# $1 window name
# $2 geometry
get_geom() {

	# the offset is an unfortunate hack to get the right
	# window size. The geometry info describes the entire 
	# window, where as the javascript resize assumes that 
	# we provide the rendering window. The offset is the 
	# diff between those two values and of course is
	# based on a standard netscape window anatomy.
	OFFSET=163
	win=$1
	( 
		set `echo $2 | tr 'x+-' '   '`
		Height=`expr ${2} \- $OFFSET`
		print -n "${win}.moveTo(${3},${4});"
        	print -n "${win}.resizeTo(${1},${Height});" 
	)
}

# emitt javascript for opening a netscape window with a
# given url and geometry
# $1 window name
# $2 window size and location 
get_url() {

	url=`echo $2 | awk '{ print $2 }'`
	geom=`echo $2 | awk '{ print $1 }'`
	echo "${url} $geom" 1>&2
	print -n "${1}=window.open(\"${url}\");"
        print -n `get_geom $1 $geom` 
}

get_script() {

        print -n "javascript:"
        typeset -i i=`expr $num_urls \- 1`
        while [ $i -gt 0 ]; do
                get_url w$i "${last_urls[$i]}"
                let "i-=1"
        done
        url=`echo ${last_urls[0]} | awk '{ print $2 }'`
        geom=`echo ${last_urls[0]} | awk '{ print $1 }'`
        print -n "location=\"$url\";"
        get_geom this $geom 
	print -n "this.focus();"
}   

#
# start kiosk browser
#
get_kiosk_value() {

        . /var/opt/SUNWut/kiosk/preferences
	
	eval echo \$$1
}

#
# startup the browser
#
start_the_browser() {

	BBUPDNDIR=`bbfind_uuid_dir $BB_TOKEN`
	DEST=$BBUPDNDIR/webtop.browser  

        if [ -f $DEST ]; then
                read_urls $DEST
		script=`get_script`
		echo "$script"
		$NETSCAPE -display $BBDISPLAY $script &
		bbnspid=$!
        else
		if [ -f /var/opt/SUNWut/kiosk/preferences ]; then
			BROWSERSIZE=`get_kiosk_value BROWSERSIZE`
			BROWSERLOCATION=`get_kiosk_value BROWSERLOCATION`
			HOMEPAGE=`get_kiosk_value HOMEPAGE`
			$NETSCAPE -display $BBDISPLAY \
				-geometry "${BROWSERSIZE}+${BROWSERLOCATION}" \
				$HOMEPAGE &
            	else
                	$NETSCAPE -display $BBDISPLAY &
		fi
		bbnspid=$!
        fi  

	if [ "$bbnspid" = "" ]; then
        	echo "failed to start the browser"
        	nspid="notset"
		return 1
	fi
	return 0
}

#
# wait for the .netscape/lock file to appear
#
wait_for_netscape_lock() {

	retry=$RETRY
	nspid="waitlock"
	while [ ! -h $LOCK -a $nspid != "notset" ]; do

    		if [ "$retry" = "0" ]; then
			nspid="notset"
        		return 1
    		fi
    		retry=`expr $retry - 1`
    		do_sleep $START_POLL_RATE
	done
	pid=`cat $BBTMPPATH/${BBUSER}.browserpid 2>/dev/null`
	if [  $? = 0 -a "$pid" != "" ]; then
		nspid=$pid
	else
		nspid="notset"
	fi
	return 0
}

#
# wait for the browser window to register
#
wait_for_window() {

	retry=$RETRY
	find_windows
	while [ "$?" != "0" -a $nspid != "notset" ]; do
    		if [ "$retry" = "0" -o ! -h $LOCK ]; then
        		return 1
    		fi
    		retry=`expr $retry - 1`
    		do_sleep $START_POLL_RATE
    		if [ $nspid != "notset" ]; then
        		find_windows
    		fi
	done
	return 0
}

#
# returns when the browser disappears from webtop
#
watch_browser() {

	find_windows
	while [ "$?" = "0" -a -h $LOCK -a $nspid != "notset" ]; do
	
    		do_sleep $WATCH_POLL_RATE
    		if [ $nspid != "notset" ]; then
        		find_windows
    		fi
	done
}

#
# execution starts here
#

mypid=$$

if [ -f $BROWSER_LOCK ]; then

	oldpid=`cat $BROWSER_LOCK`
        kill -0 $oldpid > /dev/null 2>&1

        if [ $? = 0 ]; then
		res=`/bin/ps -e -o "pid,args" | grep -v grep | \
		     grep bbstartbrowser | grep $oldpid`
		if [ "$res" = "" ]; then
                	echo "watchdog is already running..."
                	exit 2
		fi
        fi
fi

echo $mypid > $BROWSER_LOCK     

# if there is a session_ok file and it contains nothing, then 
# that means run until the file disappears.
# If the file contains something, than that has to be a number,
# which is used to limit the number of restarts of the browser.
# I>e. kiosk mode puts '1' into session_ok, therefore the browser 
# will only be started once...
if [ -f $BBTMPPATH/${BBUSER}.session_ok ]; then
	restart_cnt=`cat $BBTMPPATH/${BBUSER}.session_ok`
else
	restart_cnt=0
fi

while [ "$restart_cnt" = "" -o "$restart_cnt" -gt 0 ]; do

	if [ ! -f $BBTMPPATH/${BBUSER}.session_ok ]; then
		break
	fi

        if [ "$restart_cnt" != "" ]; then
                ((restart_cnt-=1))
        fi

	if [ ! -h $LOCK ]; then
		/usr/openwin/bin/xsetroot -display $BBDISPLAY -cursor_name watch
		$BBPATH/bin/bbns-primer $BBUSER 
		download_files
		if [ $? != 0 ]; then
    			echo "downloading of files failed"
    			local=1
    			set_lock
		fi 
		local=0
		start_the_browser
		if [ $? != 0 ]; then
			clean_up
			continue
		fi
		wait_for_netscape_lock
		if [ $? != 0 ]; then
			clean_up
			continue
                fi       
		wait_for_window
		if [ $? != 0 ]; then
			clean_up
                        continue
                fi

		/usr/openwin/bin/xsetroot -display $BBDISPLAY -cursor_name left_ptr
	else
		echo "netscape already running...."
	fi

	# netscape is running and has a window on the desktop
	watch_browser

	echo "netscape disappeared from desktop..."

	clean_up

	if [ "$local" = "0" ]; then
		local=1
    		upload_files
	fi

done

echo "" > $BROWSER_LOCK







