#!/bin/bash

function copy_file {
	if cp -r $1 $2; then
		echo "Copying $2"
	else
		echo -e "\033[0;31mCopy failed! Exiting...\033[0m" 1>&2
		exit 1
	fi
}

if [[ $EUID -ne 0 ]]; then
   echo -e "\033[0;31mThis script must be run as root!\033[0m" 1>&2
   exit 1
fi

if [[ ! ( -d "/home/ARCHI00" && ! -L "/home/ARCHI00" ) ]]; then
	echo -e "\033[0;31mMain archi system has to be installed! Exiting...\033[0m"
	exit 1
fi

if [[ ! ( -d "/home/SYSQS" && ! -L "/home/SYSQS" ) ]]; then
	echo -e "\033[0;31mMain archi system has to be installed! Exiting...\033[0m"
	exit 1
fi

pkill -SIGKILL mloop_producer
pkill -SIGKILL supervisor_tasks
pkill -SIGKILL engine

rm -Rf /mnt/tmp/*
rm -f /home/ARCHI00/DISASTER_RECOVERY/*
rm -f /home/ARCHI00/DOITMW/*
rm -f /home/ARCHI00/DOITMW/WAITW/*

echo "Installing producer..."

# PRODUCER
copy_file MLA/restore_default /home/SYSQS/restore_default
copy_file MLA/mloop_producer /home/SYSQS/mloop_producer
copy_file MLA/queue_TODO /home/SYSQS/queue_TODO

# PRE_STOS
copy_file MLA/PRE_STOS/add_trigH /home/SYSQS/PRE_STOS/add_trigH
copy_file MLA/PRE_STOS/add_trigN /home/SYSQS/PRE_STOS/add_trigN
copy_file MLA/PRE_STOS/add_trigW /home/SYSQS/PRE_STOS/add_trigW
copy_file MLA/PRE_STOS/clear_todo /home/SYSQS/PRE_STOS/clear_todo
copy_file MLA/PRE_STOS/end_todoW /home/SYSQS/PRE_STOS/end_todoW
copy_file MLA/PRE_STOS/mapstosH /home/SYSQS/PRE_STOS/mapstosH
copy_file MLA/PRE_STOS/mapstosN /home/SYSQS/PRE_STOS/mapstosN
copy_file MLA/PRE_STOS/mapstosW /home/SYSQS/PRE_STOS/mapstosW
copy_file MLA/PRE_STOS/organizeH /home/SYSQS/PRE_STOS/organizeH
copy_file MLA/PRE_STOS/organizeN /home/SYSQS/PRE_STOS/organizeN
copy_file MLA/PRE_STOS/organizeW /home/SYSQS/PRE_STOS/organizeW

# ENGINES
copy_file MLA/ENGINE/clientC /home/SYSQS/ENGINE/clientC
copy_file MLA/ENGINE/clientT /home/SYSQS/ENGINE/clientT
copy_file MLA/ENGINE/table_update /home/SYSQS/ENGINE/table_update
copy_file MLA/ENGINE/serv_ctrl /home/SYSQS/ENGINE/serv_ctrl

copy_file MLA/ENGINE/engineT /home/SYSQS/ENGINE/engineT
copy_file MLA/ENGINE/engine_t /home/SYSQS/ENGINE/engine_t
copy_file MLA/ENGINE/engine_b /home/SYSQS/ENGINE/engine_b
copy_file MLA/ENGINE/engineB /home/SYSQS/ENGINE/engineB
copy_file MLA/ENGINE/engine_n /home/SYSQS/ENGINE/engine_n
copy_file MLA/ENGINE/engineN /home/SYSQS/ENGINE/engineN

copy_file MLA/ENGINE/supervisor_daemon /home/SYSQS/ENGINE/supervisor_daemon
copy_file MLA/ENGINE/supervisor /home/SYSQS/ENGINE/supervisor

# DOIT_X (oraz wywolywane przez operators)
copy_file MLA/ENGINE/operators /home/SYSQS/ENGINE/operators
copy_file MLA/ENGINE/doit /home/SYSQS/ENGINE/doit

echo -e "\033[0;32mProducer installation Complete!\033[0m"

exit 0