#!/bin/bash

#
# This script allows to launch manderlbot and control it while running
#

# $Id$

INSTALL_DIR=/usr/lib/erlang/
ERL=/usr/bin/erl
VERSION=0.9.3

BOOT_SCRIPT="$INSTALL_DIR/lib/manderlbot-$VERSION/priv/manderlbot"
COOKIE="-setcookie mdb"
RUN_OPTIONS="-detached $COOKIE"
MANDERLBOTPATH=$INSTALL_DIR/lib/manderlbot-$VERSION/ebin

ERTS_RUN=`$ERL -version 2>&1 | tr -d '[A-Za-z] (),\f\n\r'`
ERTS_BOOT=`grep erts $MANDERLBOTPATH/../priv/manderlbot.rel | tr -d 'a-z{}"" ,\n'`

usage() {
    prog=`basename $1`
    echo "$prog start|stop|restart|status"
}

start() {
    echo "erl -sname manderlbot $RUN_OPTIONS -s manderlbot $CONF_OPT $LOG_OPT $LOG_LEVEL_OPT"
    $ERL -sname manderlbot -pa $MANDERLBOTPATH $RUN_OPTIONS -s manderlbot $CONF_OPT $LOG_OPT \
	    $LOG_LEVEL_OPT -boot_var MANDERLBOTPATH  $INSTALL_DIR
}

stop() {
    $ERL -sname control $RUN_OPTIONS -s mdb_control stop  \
         -boot_var MANDERLBOTPATH  $INSTALL_DIR
}

status() {
    pid=`ps -edaf | awk '/-[s]name manderlbot/ {print $2}'`

    if [ "zz$pid" != "zz" ]; then
	$ERL -sname control -noshell $COOKIE -s mdb_control status  \
         -boot_var MANDERLBOTPATH  $INSTALL_DIR -pa $MANDERLBOTPATH
	echo $LOG_OPT
	echo $CONF_OPT
    else
	echo "manderlbot is not running"
	echo $LOG_OPT
	echo $CONF_OPT
    fi
}

checkversion() {
    if [ $ERTS_RUN != $ERTS_BOOT ]
    then
		echo "Erlang version has changed ! [$ERTS_BOOT] != [$ERTS_RUN]"
		echo "Must create new boot files (you may have to run this one time as root ! )"
		makebootfiles
    fi
}

makebootfiles() {
    cd $MANDERLBOTPATH/..
    echo "creating boot file"
    $ERL -noshell -pa $MANDERLBOTPATH -s builder go -s init stop > /dev/null
}

while getopts ":c:l:f:" Option
do
    case $Option in
        c) CONF_OPT="-manderlbot config_file \"$OPTARG\" ";;
        f) LOG_OPT="-manderlbot log_file \"$OPTARG\" ";;
        l) LOG_LEVEL_OPT="-manderlbot log_level '$OPTARG' ";;
		*) usage ;;
    esac
done	
shift $(($OPTIND - 1))	
case $1 in
    start) 
       checkversion
       start;;

    stop)  stop;;

    status) status;;

    restart) stop && start;;

    *) usage $0
esac
