#!/bin/sh

# Copyright 2015-2023 Rivoreo

# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:

# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE
# FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


# Configure the following variables before using
REMOTE_ADDRESS=
REMOTE_PORT=
REMOTE_USER=
PRIVATE_KEY="
"

run_ssh() {
	identity_file="`mktemp`"
	trap "rm -f \"\$identity_file\"" EXIT
	chmod 600 "$identity_file"
	printf %s "$PRIVATE_KEY" > "$identity_file"
	eval "cat$input_file_indexes" | ssh -o ConnectTimeout=10 "$REMOTE_ADDRESS" -p "$REMOTE_PORT" -l "$REMOTE_USER" -i "$identity_file" -- "${0##*/} $options"
}

set -e

if [ $# = 1 ] && [ "$1" = --version ]; then
	options=--version
	input_file_indexes=' "$1"'
	run_ssh /dev/null
	exit
fi

only_stage=
options=
first_input_file=
input_file_indexes=
output_file=
end_of_options=
i=1
while [ $i -le $# ]; do
	eval "a=\"\${$i}\""
	if [ -n "$end_of_options" ] || [ "$a" = - ] || [ "${a#-}" = "$a" ]; then
		[ -z "$first_input_file" ] && first_input_file="$a"
		input_file_indexes="$input_file_indexes \"\${$i}\""
	else case "$a" in
		-[ESc])
			only_stage=${a#-}
			options="$options $a"
			;;
		-o)
			i=$((i+1))
			eval "output_file=\"\${$i}\""
			;;
		-[ODUqb])
			i=$((i+1))
			eval "options=\"\$options \$a \${$i}\""
			;;
		--)
			end_of_options=1
			;;
		-*)
			options="$options $a"
			;;
		*)
			printf '%s: BUG!\n' "$0" 1>&2
			exit 4
			;;
	esac fi
	i=$((i+1))
done

if [ -z "$input_file_indexes" ]; then
	printf '%s: no input files\n' "$0" 1>&2
	exit 1
fi

case "$output_file" in
	-)
		output_file=
		;;
	"")
		case "$only_stage" in
			E)
				;;
			S)
				output_file="${first_input_file%.*}.s"
				;;
			c)
				output_file="${first_input_file%.*}.o"
				;;
			"")
				output_file=a.out
				;;
		esac
		;;
esac

if [ -n "$output_file" ]; then
	run_ssh "$@" > "$output_file"
else
	run_ssh "$@"
fi
r=$?
[ -n "$output_file" ] && [ -z "$only_stage" ] && chmod a+x "$output_file"
exit $r
