#!/bin/sh

# This file is a part of RackTables, a datacenter and server room management
# framework. See accompanying file "COPYING" for the full copyright and
# licensing information.
#
# This is a RackTables gateway for arbitrary file export. File contents doesn't
# matter here and will only be somehow sent to the remote host for further
# processing.
#
# The only supported command is:
#
# * submit <username> <endpoint> <handler name> [filename1] [filename2] [...] 
#
# Handler name can be any string used to distinguish different file processors.
# The temporary file will be passed to a script in current directory, if it exists.
# Script name is "<handlername>.install"

user=
endpoint=
cfgfile=
MYDIR=`dirname $0`

do_submit()
{
	user=$1
	endpoint=$2
	handler=$3
	# 0 or more files
	files=$4
	# sanity checks
	if [ -z "$user" -o -z "$endpoint" -o -z "$handler" ]; then
		echo 'ERR!invalid arguments'
		return
	fi
	for cfgfile in $files; do
		if [ ! -f "$cfgfile" ]; then
			echo "ERR!File $cfgfile is missing."
			return
		fi
	done
	if [ ! -x "$MYDIR/$handler.install" ]; then
		echo "ERR!Cannot execute $MYDIR/$handler.install"
		return
	fi
	message=$("$MYDIR/$handler.install" "$user" "$endpoint" $files)
	ret=$?
	if [ $ret = 0 ]; then
		echo "OK!" "$message"
	else
		echo "ERR!Main dispatcher: handler '$handler' returned code $ret"
	fi
}

# main loop
while read cmd arg1 arg2 arg3 arg4; do
	case $cmd in
		submit)
			do_submit "$arg1" "$arg2" "$arg3" "$arg4"
			;;
		*)
			echo "ERR!unknown command $cmd"
	esac
done

exit 0
