#!/bin/sh

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

VERSION="v1.91"
AUTHOR="Gary Worsham"
MODIFIED="April 13, 2019"
# BASEDIR is used to allow the package to be installed relative to any folder location
BASEDIR=$CONNECTD_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 $0 requires root access." 1>&2
        echo "Please run sudo $0" 1>&2
	exit 1
    fi
}
##### End Version #####


isRunningCmd()
{
    isRunning=0
    # get the PID from the file that is created by this script
    if [ -f "$PIDPATH" ]; then
        runningPID="$(cat $PIDPATH)"
        # see if there is a corresponding entry in /proc
        if [ -d /proc/$runningPID ]; then
            isRunning=1
        fi
    fi
}

stopConnectd()
{
    isRunningCmd
    if [ $isRunning != 0 ]; 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
}

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

