#!/bin/sh
########################################################################
# Begin $/opt/midas/bin/replicate-file
#
# Description : Attempts to copy the specified file to the remote
#               mastercontroller
#
# Authors     : MLA
#
# Version     : 01.00
#
# Notes       : none.
#
########################################################################

#
# Constants
#

# ... source file
SOURCE_FILE=$1
TARGET_DIRECTORY=$2
DESTINATION=""


# ... errors
#     NOTE: these should be handled in CRemoteDevice.cpp.
ERROR_NONE=0
ERROR_INVALID_NUMBER_OF_ARGUMENTS=1
ERROR_NOT_MC=2
ERROR_FILE_NOT_EXIST=3
ERROR_UNKNOWN_HOST=4
ERROR_FAILED_TO_TRANSFER=5


# Include generic functions.
. /etc/rc.d/init.d/functions


#
# Have enough parameters been supplied.
#
if [ "$#" == 2 ]; then
	#
	# Determine what type of node this is executing on.
	#
	whatami TYPE ID
	
	
	#
	# Take node type specific shutdown action.
	#
	if [ "${TYPE}" = "MC" ]; then
		#
		# Running on an MC. Figure out the destination
		#
		if [ "${ID}" = "1" ]; then
			#
			# Being executed on mastercontroller 1, so transfer
			# to mastercontroller 2.
			#
			DESTINATION="192.168.19.2"
		elif [ "${ID}" = "2" ]; then
			#
			# Being executed on mastercontroller 1, so transfer
			# to mastercontroller 2.
			#
			DESTINATION="192.168.19.1"
		else
			#
			# Bay ID is invalid.
			#
			echo "ERROR: UNKNOWN MASTERCONTROLLER HOST ID ($ID)"
			exit $ERROR_UNKNOWN_HOST
		fi
		
		
		#
		# Check that the file exists.
		#
		if [ -f "$SOURCE_FILE" ]; then
			#
			# The file exists so attempt to copy it to the other MC
			#
			scp -p "${SOURCE_FILE}" "${DESTINATION}":"${TARGET_DIRECTORY}"
			if [ "$?" -eq "0" ]; then
				#
				# Finally sync the remote filesystem
				#
				ssh "${DESTINATION}" sync
				exit $ERROR_NONE
			else
				#
				# Failed to scp the file to the remote filesystem.
				#
				echo "ERROR: FAILED TO COPY FILE TO REMOTE FILE SYSTEM"
				exit $ERROR_FAILED_TO_TRANSFER
			fi
			
		else
			#
			# The specified file doesn't exist.
			#
			echo "ERROR: THE FILE ($1) DOES NOT EXIST"
			exit $ERROR_FILE_NOT_EXIST
		fi
		
	elif [ "${TYPE}" = "GUI" ]; then
		#
		# Running on the wrong node type.
		#
		echo "ERROR: REPLICATE FILE NOT AVAILABLE ON GUI NODE"
		exit $ERROR_NOT_MC
	else
		#
		# Unknown node type.
		#
		echo "ERROR: UNKNOWN NODE TYPE (" ${TYPE} ")"
		exit $ERROR_NOT_MC
	fi
	
else
	#
	# Invalid number of arguments.
	#
	echo "ERROR: INVALID NUMBER OF ARGUMENTS; ($#)"
	exit $ERROR_INVALID_NUMBER_OF_ARGUMENTS
	
fi
