#!/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 gateway retrieves the output of "show run" command (or its
# equivalent) and prints it onto stdout. When run, it accepts the
# following commands on stdin:
#
# * get8021q <endpoint> <handler> <outputfile>
#   (save remote config text into provided local file)
#
# * getcdpstatus <endpoint> <handler> <outputfile>
#   (save remote status text into provided local file)
#
# * deploy <endpoint> <handler> <inputfile>
#   (execute given text in privileged mode)

MYDIR=`dirname $0`

decode_error()
{
	case "$1" in
		1)
			echo -n 'invalid connector args'
		;;
		2)
			echo -n 'internal error 2'
		;;
		3)
			echo -n 'password not found'
		;;
		4)
			echo -n 'netcat failed'
		;;
		5)
			echo -n 'cannot create temporary files'
		;;
		6)
			echo -n 'command not supported by device'
		;;
		*)
			echo -n "unknown error $1"
		;;
	esac
}

while read command endpoint handler conftext; do
	# sanity checks
	if [ -z "$endpoint" -o -z "$conftext" -o -z "$handler" -o -z "$command" ]; then
		echo 'ERR!too few arguments in command'
		return
	fi
	[ -x "$MYDIR/$handler.connector" ] || {
		echo "ERR!Connector '$handler' is not available"
		exit 1
	}
	"$MYDIR/$handler.connector" $endpoint $command "$conftext"
	ret=$?
	if [ $ret = 0 ]; then
		echo "OK!request '$command' complete for $endpoint"
	else
		echo -n "ERR!connector error ("
		decode_error $ret
		echo ')'
	fi
done

# all error messages have been sent to stdout
exit 0
