#!/bin/bash

WORKSPACE=/usr/local/SIPServer
cd $WORKSPACE

export LD_LIBRARY_PATH=./lib/:$LD_LIBRARY_PATH

mkdir -p var

module=SIPServer
app=$module
conf=sipserver.cfg
pidfile=var/app.pid
logfile=var/app.log
chmod +x $app

start() {
    running=`ps -ef|grep '/SIPServer'|grep -v grep|wc -l`
    if [ $running -lt 1 ];then
    cd $WORKSPACE/
    	nohup ./SIPServer --cf $conf  &> $logfile &
    fi
    echo "$app is started.."
}

stop() {
    pid=`ps -ef|grep '/SIPServer'|grep -v grep |awk '{print $2}'`
    if [ -n $pid ];then 
    	kill -9 $pid
    	echo "$app stoped..."
    else
	echo "$app has already stoped..."
    fi
}

restart() {
    stop
    sleep 1
    start
}

status() {
    running=`ps -ef|grep '/SIPServer'|grep -v grep|wc -l`
    if [ $running -gt 0 ];then
        echo -n "$app now is running, pid="
	ps -ef|grep '/SIPServer'|grep -v grep |awk '{print $2}'
    else
        echo "$app is stoped"
    fi
}

menu() {
    case "$1" in
        start)
            start
            ;;
        stop)
            stop
            ;;
        restart)
            stop
            start
            ;;
        status)
            status
            ;;
        *)
            echo "Usage: $0 {start|stop|status|restart}"
            return 1
            ;;
    esac
}

menu $1

code=$?
exit ${code}
