#!/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.


# Server-side entry point for use with sshd(8)

DATA_PATH=/var/lib/compile

export PATH=/usr/local/bin:/usr/bin:/usr/sbin:/bin:/sbin
#[ -z "$TMPDIR" ] || [ ! -d "$TMPDIR" ] && export TMPDIR=/tmp

case "$1" in
	-c)
		set -f
		exec autoquit "$0" $2
		;;
	*/*|.*|*.)
		echo "Compiler not available" 1>&2
		exit 255
		;;
	"")
		cat 1>&2 << EOF
Usage: <this-shell?> <compiler> [-c|-S|-E] [-g] [-O <level>]
	[-D <macro>[=<value>]] [-U <macro>] [-v]
	[<limited-compiler-specific-options>]

Available compilers:
EOF
		for f in "$DATA_PATH"/*.sh; do
			[ -f "$f" ] || continue
			name="${f##*/}"
			printf "	%s\\n" "${name%.sh}"
		done 1>&2
		cat 1>&2 << EOF

Most compilers accept GNU style '-W', '-f' and '-m' options.
EOF
		exit 255
		;;
	*)
		WRAPPER="$DATA_PATH/$1.sh"
		if [ ! -f "$WRAPPER" ]; then
			echo "Compiler not available" 1>&2
			exit 255
		fi
		;;
esac

[ $# = 2 ] && [ "$2" = --version ] && exec sh "$WRAPPER" --version

shift

ONLY_STAGE=
DEBUG=
OPTIMIZATION=
DEFINE=
UNDEFINE=
VERBOSE=

extra_options=

while getopts EScgO:D:U:vW:f:m:q:b: c
do case $c in
	E|S|c)
		ONLY_STAGE=$c
		;;
	g)
		DEBUG=1
		;;
	O)
		OPTIMIZATION="$OPTARG"
		;;
	D)
		DEFINE="$OPTARG
$DEFINE"
		;;
	U)
		UNDEFINE="$OPTARG
$UNDEFINE"
		;;
	v)
		VERBOSE=1
		;;
	W|f|m)
		if [ $c = W ] && [ "${OPTARG#[pal],}" != "$OPTARG" ]; then
			echo "Passing options directly to backend programs is not allowed" 1>&2
			exit 255
		fi
		extra_options="$extra_options -$c$OPTARG"
		;;
	q|b)
		extra_options="$extra_options -$c $OPTARG"
		;;
	*)
		exit 255
		;;
esac done

export ONLY_STAGE DEBUG OPTIMIZATION DEFINE UNDEFINE VERBOSE
ulimit -t 120
ulimit -f 2048	# 1 MiB
ulimit -m 1048576
exec sh "$WRAPPER" $extra_options
