if [ -x /bin/which ] ; then which=/bin/which
elif [ -x /usr/bin/which ] ; then which=/usr/bin/which
else which=which ; fi

dirname=`$which dirname`
[ -x "$dirname" ] || dirname=/bin/dirname
cfg="`$dirname \"$0\"`/config"

usage() {
	echo "Usage: cat [ -h host] UUID [SUFFIX] OUTFILE" >&2
	exit 1
}

if [ "$1" = "-h" ] ; then
	shift

	if [ $# -eq 3 ] ; then
		## Workaround for Win32/Cygwin glitch: empty argument disappears from ARGV
		host="$1" ; shift
		id="$1"; shift
		suffix=""
		outfile="$1"; shift
	elif [ $# -eq 4 ] ; then
		host="$1" ; shift
		id="$1"; shift
		suffix="$1"; shift
		outfile="$1"; shift
	else
		usage
	fi

	. "$cfg"

	if uname | grep -q ^CYGWIN ; then
		outfile=`cygpath "$outfile"`
	fi

	(
        	echo "id=\"$id\"" ;
        	echo "suffix=\"$suffix\"" ;
        	echo "prefix=\"$rprefix\"" ;
        	cat "$bindir/cat.sh"
	) | eval $sshcmd > "$outfile"
	exitcode=$?
	if [ $exitcode -eq 255 ] ; then
		echo "SSH client has failed. Click 'Push SSH Key' button in Table View to verify remote host key for host '$host'" >&2
		exit 255
	else
	        exit $exitcode
	fi
else
	if [ $# -eq 2 ] ; then
		## Workaround for Win32/Cygwin glitch: empty argument disappears from ARGV
		id="$1" ; shift
		suffix=
		outfile="$1"; shift
	elif [ $# -eq 3 ] ; then
		id="$1" ; shift
		suffix="$1" ; shift
		outfile="$1"; shift
	else
		usage
	fi

	. "$cfg"

	if uname | grep -q ^CYGWIN ; then
		outfile=`cygpath "$outfile"`
	fi

	## The worker script will use $prefix and $idsuffix variables
	. "$bindir/cat.sh" > "$outfile"
fi
