#!/bin/bash
# 
# This is the service control script for SkyForm AI monitoring agent
#
# ckconfig: 35 99 01
# description: olmon

### BEGIN INIT INFO
# Provides: Teraproc
# Required-Start: $local_fs $remote_fs $network $syslog
# Required-Stop: $local_fs $remote_fs $syslog $network
# Default-Start:  3 4 5
# Default-Stop: 0 1 6
# Short-Description: olmon
# Description: SkyForm AI Monitoring and Analytics solution
### END INIT INFO

# -------------- Modify the following two lines
export CB_ENVDIR=/cubetop/etc
export OLMONBIN=/cubetop/sbin
# ---------------------------------------------
logdir=/cubetop/log

if [ -f $CB_ENVDIR/limits.sh ]; then
    . $CB_ENVDIR/limits.sh
fi

function getips() {
    ip=`ps -ef | grep $OLMONBIN/olcol | grep -v grep | awk '{print $2}'`
}

function kill_daemons()
{
    getips
    if [ "$ip" != '' ]; then
        kill $ip
    fi
}

function help()
{
    echo $0 'start|stop|restart|status'
    exit 0
}


if [ $# -lt 1 ]; then
    help
fi

opcode=$1
if [ $opcode == 'restart' ]; then
    opcode="start"
    echo Stopping service: $0
fi

case $opcode in
    'stop')
        echo Stopping serivce: $0
        kill_daemons
        exit 0
        ;;

    'start')
        kill_daemons 
        echo Starting service: $0
        while [ ! -f $OLMONBIN/olcol ]; do
            sleep 5
        done
        logfile=$logdir/olmon.log.`hostname -s`
        if [ -f $logfile ]; then
            mv $logfile $logfile.old
        fi
        touch $logfile
        rm -f /tmp/.olmon.url /tmp/olmon*
        #chown -R ADMIN: $logfile
        
        #su ADMIN -c $OLMONBIN/olcol
        $OLMONBIN/olcol
        sleep 1
        getips
        if [ "$ip" == '' ]; then
             echo Starting service $0 [failed]
             exit 1
        else
             echo Starting service $0 [OK]
             exit 0
        fi
        ;;

     'status')
         getips
         pids=`echo $ip`
         echo "olcol pid: <$pids>"
         exit 0
         ;;

     *)
         help
         ;;
esac
