#!/bin/sh

# Web Control Panel service script
# chkconfig: 345 80 50
# description: start or stop Avaya Web Control Panel

# configuration files
WEBCONTROL_CONFIG=/etc/sysconfig/webcontrol
IPOFFICE_CONFIG=/etc/sysconfig/ipoffice
ISA_RELEASE=/opt/Avaya/ISA_release
APPL_RELEASE=/opt/Avaya/APPL_release
ABG_RELEASE=/opt/Avaya/ABG_release
ABE_RELEASE=/opt/Avaya/ABE_release
APC_RELEASE=/opt/Avaya/APC_release

function set_env_ipoffice {
        if [ -f $IPOFFICE_CONFIG ]; then
            . $IPOFFICE_CONFIG
        else
            echo "warning: $IPOFFICE_CONFIG configuration file is missing"
        fi
}

if [ -f /etc/sysconfig/i18n ]; then
    . /etc/sysconfig/i18n
    export OS_LANG=$LANG
fi
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8

if [ -f $WEBCONTROL_CONFIG ]; then
    . $WEBCONTROL_CONFIG
else
    echo "error: $WEBCONTROL_CONFIG configuration file is missing"
    exit 1
fi

start() {
    PID=$(pgrep -f webcontrol.py)

    if [ ! -z "$PID" ]; then
        echo "Web control interface is already running"
        exit 1
    fi

    if [ -f $ISA_RELEASE ]; then
        . $ISA_RELEASE
        set_env_ipoffice
    elif [ -f $APPL_RELEASE ]; then
        . $APPL_RELEASE
    elif [ -f $APC_RELEASE ]; then
        . $APC_RELEASE
    elif [ -f $ABG_RELEASE ]; then
        . $ABG_RELEASE
    elif [ -f $ABE_RELEASE ]; then
        . $ABE_RELEASE
        set_env_ipoffice
    else
        echo "error: unknown release type"
        exit 1
    fi

    if [ "$1" == "local" ]; then
        export WEBCONTROL_PORT=7070
        export WEBCONTROL_HOME=.
        export WEBCONTROL_LOG_DIR=log
    fi
    chown -R $WEBCONTROL_USER:$WEBCONTROL_USER $WEBCONTROL_HOME #make sure permissions are correct
    su $WEBCONTROL_USER -c "mkdir -p $WEBCONTROL_LOG_DIR"
    cd $WEBCONTROL_HOME
    su $WEBCONTROL_USER -c "./webcontrol.py $WEBCONTROL_PORT &> $WEBCONTROL_LOG_DIR/web.log" &> /dev/null &
    echo "Web control interface started"
    exit 0
}

stop() {
    PID=$(pgrep -f webcontrol.py)

    if [ -z "$PID" ]; then
        echo "Web control interface is not running"
        exit 1
    fi

    STOPPED=$(pkill -f webcontrol.py)

    if $STOPPED
    then
        echo "Web control interface stopped"
    else
        echo "Unable to stop web control interface"
        exit 1
    fi
    exit 0
}

status() {
    PID=$(pgrep -f webcontrol.py)

    if [ -z "$PID" ]; then
        echo "Web control interface is stopped"
    else
        echo "Web control interface is running"
    fi
    exit 0
}

case $1 in
    start)
        start $2
        ;;
    stop)
        stop
        ;;
    restart)
        stop
	    sleep 5
        start $2
        ;;
    status)
        status
        ;;
    *)
        echo "usage: $0 [start | stop | restart | status]"
        exit 1
esac
