#!/bin/sh
#
# toolchain detection
#

COMPILERS="cc gcc clang suncc"
unset CC_ARG_CHECKED
unset TOOLCHAIN_DETECTION_ERROR
unset TOOLCHAIN_NAME

check_compiler()
{
    cat > $TEMP_DIR/test.c << __EOF__
/* test file */
#include <stdio.h>
int main(int argc, char **argv) {
#if defined(__GNUC__)
    printf("gcc\n");
#elif defined(__clang__)
    printf("clang\n");
#elif defined(__sun)
    printf("suncc\n");
#else
    printf("unknown\n");
#endif
    return 0;
}
__EOF__
    rm -f $TEMP_DIR/checkcc
    $1 -o $TEMP_DIR/checkcc $CFLAGS $LDFLAGS $TEMP_DIR/test.c
    
    if [ $? -ne 0 ]; then
        return 1
    fi
    return 0
}

printf "detect toolchain... "

for COMP in $COMPILERS
do
    check_compiler $COMP
    if [ $? -ne 0 ]; then
        if [ $COMP = $CC ]; then
            echo "$CC is not a working C Compiler"
            TOOLCHAIN_DETECTION_ERROR="error"
            break
        fi
    else
        TOOLCHAIN_NAME=`$TEMP_DIR/checkcc`
        TOOLCHAIN_CC=$COMP
        echo $TOOLCHAIN_NAME
        break
    fi
done

TOOLCHAIN_LD=$TOOLCHAIN_CC

if [ -z TOOLCHAIN_NAME ]; then
    TOOLCHAIN_DETECTION_ERROR="error"
else
    cat >> $TEMP_DIR/config.mk << __EOF__
# toolchain
__EOF__
	echo "CC = ${TOOLCHAIN_CC}" >> $TEMP_DIR/config.mk
    echo "LD = ${TOOLCHAIN_LD}" >> $TEMP_DIR/config.mk
    
    if [ -e "make/${TOOLCHAIN_NAME}.mk" ]; then 
        echo "include \$(BUILD_ROOT)make/${TOOLCHAIN_NAME}.mk" >> $TEMP_DIR/config.mk
    fi
fi
