#!/bin/sh

#  connectd_launch - template file for start/stop of individual services
#  
#
#  remot3.it, Inc. Copyright 2019. All rights reserved.
#

VERSION="v1.8"
AUTHOR="Gary Worsham"
MODIFIED="January 02, 2019"
# BASEDIR is used to allow the package to be installed relative to any folder location
BASEDIR=
. "$BASEDIR"/usr/bin/connectd_options

CONNECTD_PORT=
DAEMON=connectd."$PLATFORM"
PIDPATH="$PID_DIR"/"$CONNECTD_PORT".pid
LOG_DIR=/tmp

##### Version #####
displayVersion()
{
    printf "Connectd daemon start/stop script Version: %s \n" "$VERSION"
    # check for root user at this point
    if ! [ "$(id -u)" = 0 ]; then
        echo "Running $CONNECTD_PORT requires root access." 1>&2
        echo "Please run sudo $CONNECTD_PORT" 1>&2
	exit 1
    fi
}
##### End Version #####


isRunningCmd()
{
	if [ -f "$PIDPATH" ]; then
		runningPID="$(cat $PIDPATH)"
	fi
	# see if there is ANY matching line with connectd and $CONNECTD_PORT.conf
	# isRunning will be 0 if NOTHING matches
	isRunningLine=$(ps "$PSFLAGS" | grep connectd | grep -w "$CONNECTD_PORT.conf" | grep -v grep)
	isRunningps=$(echo -n $isRunningLine | wc -w)
	ps "$PSFLAGS" | grep connectd | grep -w "$CONNECTD_PORT.conf" | grep -v grep > /tmp/connectdps.txt
	#-------------	
	# this next part is to ensure, when  remote.it connectd services are installed on
	# a VM and containers within that VM, that we can correctly identify 
	# the PID corresponding the the service running on the VM. This is the
	# one which has a matching PID in /var/run/$CONNECTD_PORT.pid
	#-------------	
	isRunning=0
	while read p; do
  	    psPID=$(echo $p | awk '{ print $1 }')
	    if [ "$psPID" = "$runningPID" ]; then
                if [ "$isRunningps" != "0" ]; then
#		echo "Matching PID! $psPID"
		    isRunning=1
		    return
	        fi
            fi
	done < /tmp/connectdps.txt
}

stopConnectd()
{
	isRunningCmd
	if [ $isRunning != 0 ]; then
            if [ $psPID = $runningPID ]; then
		echo "Stopping $CONNECTD_PORT..."
		kill $runningPID 2> /dev/null
		rm $PIDPATH 2> /dev/null
	    else
		echo "$CONNECTD_PORT is not currently active. Nothing to stop."
	    fi
        fi
}

startConnectd()
{
	isRunningCmd
	if [ $isRunning = 0 ]; then
		echo "Starting $CONNECTD_PORT..."
		$BIN_DIR/$DAEMON -f $CONNECTD_CONF_DIR/$CONNECTD_PORT.conf -d $PID_DIR/$CONNECTD_PORT.pid > $LOG_DIR/$CONNECTD_PORT.log
		tail $LOG_DIR/$CONNECTD_PORT.log
	else
		echo "$CONNECTD_PORT is already started"
	fi
}

restartConnectd()
{
	stopConnectd
	sleep 2
	startConnectd
}

displayVersion

if [ -z $1 ]; then
	echo "You need one of the following arguments: start|stop|restart"
	exit
elif [ "$(echo "$1" | tr '[A-Z]' '[a-z]' | tr -d ' ')" = "stop" ]; then 
	stopConnectd
elif [ "$(echo "$1" | tr '[A-Z]' '[a-z]' | tr -d ' ')" = "start" ]; then
	startConnectd
elif [ "$(echo "$1" | tr '[A-Z]' '[a-z]' | tr -d ' ')" = "restart" ]; then
	restartConnectd
else
	echo "This option is not supported"
fi

