#! /bin/bash

#!/bin/bash
# chkconfig: 345 80 20

#set -x

DTHOME=/usr/local/dingtone
LISTPORT=443
BINNAME=xedge

check_port(){
    pid=$(ps -ef | grep "./$BINNAME$" | grep -v grep | awk '{print $2}')
    info=`netstat -anop | grep $LISTPORT | grep LISTEN`

    if [ $? -eq 0 ]; then
        occpid=`echo $info | awk '{print $7}' | sed  's/\([0-9]*\).*/\1/g'`
        echo "Port ${LISTPORT} is occupied, pid is $pid, real occupied by $occpid"
        if [ "$pid" != "" ] && [ $pid -eq $occpid ]; then
            echo "pid :$pid is bind on port ${LISTPORT} successfully"
        else
            echo "Port ${LISTPORT} is occupied by $occpid, will kill it"
            if [ "$pid" != "" ]; then
                kill -9 $pid
            fi
            if [ "$occpid" != "" ]; then
                kill -9 $occpid
            fi
        fi
    else
        echo "Port ${LISTPORT} is occupied by ${BINNAME} server"
    kill -9 $pid
    fi
}
getpid() {
    local i
    for i in $(ps -ef | grep "./$BINNAME$" | grep -v grep | awk '{print $2}')
    do
        echo $i
    done    
}

get_monitor_pid() {
    local i
    for i in $(ps -ef | grep "xedge-monitor$" | grep -v grep | awk '{print $2}')
    do
        echo $i
    done    
}

start() {
    local pid=$(getpid)
    if [ "$pid" != "" ]; then
        echo "Dingtone ${BINNAME} sever is already running with pid=$pid"
        return 0
    fi
    
    if [ ! -e $DTHOME/$BINNAME ]; then
        echo "Dingtone ${BINNAME} server is not properly installed"
        return 1
    fi
    
    echo -n "Starting Dingtone ${BINNAME} server"
    
    mkdir -p /var/log/dingtone
    
    nohup $DTHOME/xedge-monitor > /dev/null &
    sleep 10
    pid=$(getpid)
    if [ "$pid" != "" ]; then
        echo " succeeded"
    else
        echo " failed"
    fi

 #   check_port
}

stop() {
    local pid=$(getpid)
    if [ "$pid" != "" ]; then
    echo "Archiving ${BINNAME}..."
    kill -12 $pid

        echo -n "Stopping Dingtone ${BINNAME} server"

        kill $(get_monitor_pid)
        kill $pid >/dev/null 2>&1
        sleep 5
#        kill -9 $BINNAME
		killall -9 $BINNAME
        sleep 1
 
        pid=$(getpid)
        if [ "$pid" == "" ]; then
            echo " succeeded"
        else
            echo " failed"
        fi       
    else
        echo "Dingtone ${BINNAME} server is already stopped"
    fi
}

status() {
    local pid=$(getpid)
    if [ "$pid" != "" ]; then
        echo "Dingtone ${BINNAME} server is currently running with pid: $pid"
    else
        echo "Dingtone ${BINNAME} server is not running"
    fi
}

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

exit $?