#!/bin/bash
#
# Copyright (c) 2018 Jiri Svoboda
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
#   notice, this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
# - The name of the author may not be used to endorse or promote products
#   derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# C Compiler (cc) wrapper
# HelenOS Cross Compiler Wrapper (XCW)
# Facilitate cross-compiling external software to HelenOS
#



XCW="$(dirname "$0")"
BUILD_ROOT="$(dirname "$(dirname "$(dirname "$XCW")")")"
if [ -z "$EXPORT_DIR" ]; then
	EXPORT_DIR="$BUILD_ROOT/export"
fi

HELENOS_EXPORT_ROOT="$EXPORT_DIR"

source "${EXPORT_DIR}/config.sh"

# CC is a compilation driver, so we should check which stage of compilation
# is actually running and select which flags to provide. This makes no
# difference for GCC, but e.g. clang warns when a flag is provided that is
# unused

needs_cflags=true
needs_ldflags=true

for flag in "$@"; do
	case "$flag" in
		-E)
			needs_cflags=false
			needs_ldflags=false
			break
			;;
		-c|-S)
			needs_ldflags=false
			break
			;;
	esac
done

flags="-fwide-exec-charset=UTF-32LE -finput-charset=UTF-8 -fexec-charset=UTF-8"
flags="$flags -isystem ${HELENOS_EXPORT_ROOT}/include/libc -idirafter ${HELENOS_EXPORT_ROOT}/include"

if $needs_cflags; then
	flags="$flags -O3 \
	    -Wall -Wextra -Wno-clobbered -Wno-unused-parameter -Wmissing-prototypes \
	    -std=gnu99 -Werror-implicit-function-declaration -Wwrite-strings -ggdb"

	flags="$flags $HELENOS_CFLAGS"
fi

if $needs_ldflags; then
	flags="$flags $HELENOS_LDFLAGS"
fi

flags="$flags $@"

if $needs_ldflags; then
	flags="$flags $HELENOS_LDLIBS"
fi

echo "helenos-cc" "$@"
PATH="$HELENOS_CROSS_PATH:$PATH" "${HELENOS_TARGET}-gcc" $flags
