#!/usr/bin/env bash

if [ $EMBOX_GCC_ENV ] && [ -f $EMBOX_GCC_ENV ]; then
	. $EMBOX_GCC_ENV
else
	echo "No EMBOX_GCC_ENV is set" >&2
	exit 1
fi

cppflags="$EMBOX_DEPS_CPPFLAGS_BEFORE $EMBOX_IMPORTED_CPPFLAGS $EMBOX_DEPS_CPPFLAGS_AFTER"

cmd=$(basename $0)
case $cmd in
	*-gcc|*-clang) arg_line_before="$EMBOX_IMPORTED_CFLAGS";;
	*-g++)         arg_line_before="$EMBOX_IMPORTED_CXXFLAGS";;
	*)             echo "Unknown flags for $cmd"; exit 1;;
esac

case $EMBOX_GCC_LINK in
	full) arg_line_after="$cppflags $EMBOX_IMPORTED_LDFLAGS $EMBOX_IMPORTED_LDFLAGS_FULL";;
	*)    arg_line_after="$cppflags $EMBOX_IMPORTED_LDFLAGS -Wl,-r";;
esac

case " $@ " in
	*" -c "*) arg_line_after="$cppflags";;
	*" -E "*) arg_line_after="$cppflags" arg_line_before="";;
	*" -shared "*) echo -e "\n\nCan't build shared objects\n\n"; exit 1;;
	*" -l"*) $0 $(for i in "$@"; do echo ${i/#-l*/}; done); exit $?;;
	*" -I/usr/"*) $0 $(for i in "$@"; do echo ${i/#-I\/usr\/*/}; done); exit $?;;
esac

arg_line_before="$(for i in $arg_line_before; do echo ${i/$PWD/.}; done)"
arg_line_after="$(for i in $arg_line_after; do echo ${i/$PWD/.}; done)"

if [[ "$cmd" == *clang ]]; then
	clang $arg_line_before "$@" -target arm-none-eabi $arg_line_after
	exit $?
else
	# arch-embox-gcc args ("$@") follow imported cflags and cxxflags and can override them.
	# Imported cppflags follow arch-embox-gcc args ("$@") for '#include_next' to work.
	# Imported ldflags must follow input files from arch-embox-gcc args ("$@").
	$EMBOX_CROSS_COMPILE${cmd#arch-embox-} $arg_line_before "$@" $arg_line_after
	exit $?
fi
