#!/bin/bash

PROJECT_ROOT=`pwd`
HOST=127.0.0.1
PORT=3033
OUT=$HOME/var/log/bibmate.out
ERR=$HOME/var/log/bibmate.err

DJANGO_PID="$PROJECT_ROOT/django.pid"
LIGHTTPD_PID="$PROJECT_ROOT/lighttpd.pid"

function runDjango {
    python manage.py runfcgi host=$HOST port=$PORT \
        method=threaded \
        pidfile=$DJANGO_PID \
        daemonize=true \
        outlog=$OUT \
        errlog=$ERR
}

function runHttpd {
    lighttpd -f lighttpd.conf
}

function killemall {
    if [ -f $DJANGO_PID ]; then
        kill `cat -- $DJANGO_PID`
        rm -f -- $DJANGO_PID
    fi

    if [ -f $LIGHTTPD_PID ]; then
        kill `cat -- $LIGHTTPD_PID`
        rm -f -- $LIGHTTPD_PID
    fi
}

if [ "$1" == "start" ]
then
    killemall
    runDjango
    runHttpd
elif [ "$1" == "stop" ]
then
    killemall
else
    echo "Usage: server.sh (start|stop)" >&2
    exit 1
fi
