#!/bin/sh

# start bweb with lighttpd

BASE=$(dirname $0)

if [ -f $PWD/html/bweb.js ]; then
   BWEBBASE=$PWD

elif [ -f $PWD/../html/bweb.js ]; then
    BWEBBASE=$(dirname $PWD)

elif [ -f $BASE/html/bweb.js ]; then
    BWEBBASE=$BASE

elif [ -f $BASE/../html/bweb.js ]; then
    BWEBBASE=$(cd $BASE; dirname $(pwd))

else
    echo "Can't determine bweb installation directory"
    exit 1
fi

if [ ! -f $BWEBBASE/bweb.conf ]; then
    echo "Making configuration template in $BWEBBASE/bweb.conf"
    cat > $BWEBBASE/bweb.conf <<EOF
\$VAR1 = { template_dir => '$BWEBBASE/lang',
           bconsole => 'bconsole -n',
           fv_write_path => '/tmp/',
 };
EOF
fi

host=$(awk -F'"' '/bind/ { print $2 }' $BWEBBASE/script/httpd.conf)
port=$(awk '/port/ { print $3 }' $BWEBBASE/script/httpd.conf)

echo "Using bweb on $BWEBBASE,  use firefox http://$host:$port"
export BWEBBASE
export BWEBCONF=$BWEBBASE/bweb.conf

if [ x$1 = x -o x$1 = xstart ]; then
    lighttpd -f $BWEBBASE/script/httpd.conf

    if [ $? -ne 0 ]; then
        echo "Something is wrong with lighttpd, be sure that it is installed"
        exit $?
    fi
fi

if [ x$1 = xstop ]; then
    killall lighttpd
fi
