#!/bin/bash
#
# Startup script for Verax SNMP Agent Simulator (for Linux & UNIX)
# Copyright (c) Verax Systems
# 
# chkconfig: 5 98 55
# description: Verax SNMP Agent Simulator service
#


#######################################
# Please verify the configuration     # 
# file location.                      #
#######################################

# Path to configuration file (e.g. '/etc/verax.d/simulator.conf')
CONF_SIM_FILE='/etc/verax.d/simulator.conf'

SIMULATOR_WEB_CLIENT_JAR=SnmpAgentSimulator-jetty-console.war
VS_WEB_CLIENT_CONTEXT=/SnmpAgentSimulator

# Arguments to pass to the simulator during startup. 
# Note, that ARGS should start with space
ARGS=''

# Please do not change the script beyond this line!

for line in $(cat ${CONF_SIM_FILE}|grep -v '^#')
do
	eval "VS_${line}"
done

cd $VS_SIMULATOR_HOME

case "$1" in
    console)
	${VS_JRE_HOME}java -jar $VS_SIMULATOR_HOME/jar/snmp-simulator-rmi-client.jar $@
	;;
    start) 
        echo "Verax SNMP Agent Simulator. Copyright (c) Verax Systems. All rights reserved."
	ulimit -n 100000
	nohup ${VS_JRE_HOME}java -jar $VS_SIMULATOR_HOME/jar/snmp-simulator-server.jar$ARGS &> /dev/null &
	
        echo "Verax SNMP Agent Simulator started. Loading network configuration..."
        sleep 2
        ;;
    stop)
        echo "Stopping Verax SNMP Agent Simulator..."
        if [ -z "$VS_SERVER_PORT" ]
        then
            VS_SERVER_PORT=43500
        fi
        ${VS_JRE_HOME}java -jar $VS_SIMULATOR_HOME/jar/snmp-simulator-rmi-client.jar -c END -p $VS_SERVER_PORT $@
        ;;
    status)
        status=`ps -ef | grep "snmp-simulator-server.jar$ARGS" | grep -v grep`
        if [ "$status" == "" ]
        then
            echo "Verax SNMP Agent Simulator stopped."
        else
            echo "Verax SNMP Agent Simulator running."
	    CNT=`cat $VS_SIMULATOR_HOME/conf/created_interfaces.txt | wc -l`
            echo "Number of virtual interfaces created: `expr $CNT - 1`."
        fi
        exit 0
        ;;
    webconsole-start)
        echo "Verax SNMP Simulator Console. Copyright (c) Verax Systems. All rights reserved."
	WEB_PORT='8080'
	if [ ! -z "$VS_WEBCONSOLE_PORT" ]
	then
	    WEB_PORT=${VS_WEBCONSOLE_PORT}
	fi
	nohup ${VS_JDK_HOME}java -jar $VS_SIMULATOR_HOME/jar/$SIMULATOR_WEB_CLIENT_JAR --headless --contextPath $VS_WEB_CLIENT_CONTEXT --port $WEB_PORT &> /dev/null &
	;;
    webconsole-stop)
        echo "Stopping Verax SNMP Simulator Console..."
	PID=`ps -ef | grep "SnmpAgentSimulator-jetty-console.war" | grep -v grep | tr -s ' ' | cut -d ' ' -f 2`
	kill $PID
	;;
    *)
        echo "Usage: $0 {console|start|stop|status|webconsole-start|webconsole-stop}"
        exit 1
        ;;
esac

exit 0
