#!/bin/bash

INSTALLATION_DIR=`pwd`
LOG_FILE_PATH=logs/info0.log
PLIST_FILE_PATH=com.princity.agent.plist
AGENT_DIR_PLACEHOLDER='\${AGENT_DIR}'
START_UP_LOG_PLACEHOLDER='\${LOG_FILE_PATH}'
START_UP_ERR_LOG_PLACEHOLDER='\${ERROR_FILE_PATH}'

PROCESS_TIMEOUT=10
PROCESS_CHECK_INTERVAL=1
AGENT_KEY=
PID=

msg_exit() {
	sleep 2
	echo "*******************"
	echo "$1"
	echo "*******************"
	exit 1
}
err_exit() {
	msg_exit "ERROR: $1"
}
success_exit() {
	msg_exit "Agent successfully installed"
}

read_params() {
	echo "Agent installation"
	echo "--------------------"
	echo "Enter agent key: "
	read AGENT_KEY
	(echo "$AGENT_KEY" | grep -Eq "^([a-zA-Z]{4}-){3}[a-zA-Z]{4}$") || err_exit "Agent key must have 4 group of 4 characters separated by '-' mark"
}

start_agent() {
	PID=`ps aux | grep -v grep | grep "\-jar princity.jar config/" | awk '{print $2}'`
	if [ -n "$PID" ]; then
		kill $PID
		sleep 2
	fi

	./run.sh $AGENT_KEY &

	PID=`ps aux | grep -v grep | grep "\-jar princity.jar config/" | awk '{print $2}'`
	if [ -z "$PID" ]; then
		err_exit "Process could not be started"
	fi
}

copy_plist() {
	ESCAPED_INSTALLATION_DIR=$(echo $INSTALLATION_DIR | sed 's_/_\\/_g');
	LOG_PATH="$ESCAPED_INSTALLATION_DIR\/logs\/start_up.log"
	ERR_PATH="$ESCAPED_INSTALLATION_DIR\/logs\/start_up.err"

	sed -i -e "s/$AGENT_DIR_PLACEHOLDER/$ESCAPED_INSTALLATION_DIR/g" $PLIST_FILE_PATH
	sed -i -e "s/$START_UP_LOG_PLACEHOLDER/$LOG_PATH/g" $PLIST_FILE_PATH
	sed -i -e "s/$START_UP_ERR_LOG_PLACEHOLDER/$ERR_PATH/g" $PLIST_FILE_PATH

	cp $PLIST_FILE_PATH /Library/LaunchDaemons/
}

if [ `id -u` -ne 0 ]; then
	err_exit "Script must be run as root"
fi

read_params
start_agent
copy_plist

echo "Checking process with pid = $PID ..."
while (( PROCESS_TIMEOUT > 0 )); do
	(echo `tail $LOG_FILE_PATH` | grep "Successfully connected") && success_exit
	PROCESS_TIMEOUT=$(($PROCESS_TIMEOUT - $PROCESS_CHECK_INTERVAL))
	sleep $PROCESS_CHECK_INTERVAL;
done

err_exit "Process could not be started"


