#!/bin/sh

# Awk compile wrapper-script for 'compile.sh'.
# See that script for syntax and more info.
#
# This script does not actually "compile" the source, but writes a
# shell script that will function as the executable: when called, it
# will execute the source with the correct interpreter syntax, thus
# allowing this interpreted source to be used transparently as if it
# was compiled to a standalone binary.

DEST="$1" ; shift
MEMLIMIT="$1" ; shift
MAINSOURCE="$1"

# Syntax check based on: https://stackoverflow.com/a/7212314
for j in "$@" ; do
	awk -f $j -- 'BEGIN { exit(0) } END { exit(0) }'
	EXITCODE=$?
	[ "$EXITCODE" -ne 0 ] && exit $EXITCODE
done

# We construct here the list of source files to be passed to awk:
FILEARGS=''
for i in "$@" ; do
	FILEARGS="$FILEARGS -f '$i'"
done

# Write executing script:
cat > "$DEST" <<EOF
#!/bin/sh
# Generated shell-script to execute awk interpreter on source.

# Detect dirname and change dir to prevent file not found errors.
if [ "\${0%/*}" != "\$0" ]; then
	cd "\${0%/*}"
fi

# Add -v ONLINE_JUDGE=1 -v DOMJUDGE=1 below to make it easier for teams to do
# local debugging.
exec awk $FILEARGS "\$@"
EOF

chmod a+x "$DEST"

exit 0
