#!/bin/bash
#
# Start/stop TeamCall Server under Linux
#
# Copyright (c) 1997-2004, 2006, 2010-2011 by ilink Kommunikationssysteme GmbH.  All Rights Reserved.
#
# Calling user must be root!
# Modify according to your needs.
#


### BEGIN INIT INFO
# Provides:             TeamCall Server
# Required-Start:       
# Required-Stop:        
# Default-Start:        2 3 5
# Default-Stop:         2 3 5 6
# Short-Description:    Teamcall Server CTI middleware by ilink Kommunikationssysteme GmbH
### END INIT INFO


# Set your PBX type 
# For valid types use ./CSTAServer --help
# Example: PBX=a4400
PBX=%%PBX%%

# Set the node name for TeamCall server instance
# Using different node names is useful for a TeamCall multi node installation.
# Example: NODENAME=berlin (do not use spaces or special caracters for NODENAME)
NODENAME=%%NODE%%

# Set the main TeamCall install path
# Example: TCINSTALL=/usr/local/ilink/teamcall
TCINSTALL=%%TCINSTALL%%


### DO NOT MODIFY THE SCRIPT BELOW THIS POINT ###

NODEDIR="$TCINSTALL/node_$NODENAME"
SERVER="CSTAServer_$NODENAME"
SERVERNAME="TeamCall Server $NODENAME"

# Get pid of TeamCall process
PID=`ps -C $SERVER -f | grep "$SERVER -c" | awk '{print $2}'`

case $1 in
start)
	if [ "X$PID" != "X" ]; then
		echo "$SERVER is already running";
		exit 0;
	fi

	if [ -f "$NODEDIR/Default.conf" ]; then
		cd $NODEDIR
		"./$SERVER" -c "$NODEDIR/Default.conf" -pbx $PBX 2> /dev/null 1>&2 &
	fi

	x=0
	while [ $x -lt 10 ]; do
		# Get pid of TeamCall process
		PID=`ps -C $SERVER -f | grep "$SERVER -c" | awk '{print $2}'`
		if [ "X$PID" != "X" ]; then
			echo "$SERVERNAME started."
			exit 0;
		fi
		sleep 0.5
		let x++
	done
	echo "$SERVERNAME not started."
;;

stop)
	if [ "X$PID" == "X" ];then
		echo "$SERVER is not running";
	else
		kill -15 $PID
		echo "$SERVER stopped."
	fi
;;

status)
	if [ "X$PID" == "X" ]; then
		echo "$SERVER is not running";
		exit 0;
	else
		echo "$SERVER is running";
		exit 0;
	fi
;;

restart)
	if [ "X$PID" == "X" ]; then
		echo "$SERVER is not running";
	else
		stop
	fi
	start
;;

*)
    echo "Invalid argument: " $1
    echo "Use [start, stop, restart, or status]"
;;

esac

exit

