#!/bin/bash

#
# Search for GCC or XL C/C++, former if both exist
#
# To add another compiler, just create Makefile.XXX and add XXX to $CCS
#
# To prevent ugly Makefile extensions, underscore and chars following it
# in the name XXX are automatically removed before locating relevant
# Makefile. This is why compiler "xlc_r" has Makefile extension "xlc".
# This can be disabled if neccessary.
#

CCS="xlc_r gcc"

#
# Look for supported compilers
#
for c in $CCS; do
    if CCPATH=`which $c 2>&1` && [ -z "${CCPATH%%/*}" ]; then
        CC="$c"
        break
    fi
done

#
# Make a link to a proper Makefile.*
#
if [ -z "$CC" ]; then
    echo "Unable to find GNU GCC or IBM XL C/C++. Fix your PATH!"
    exit 1
else
    echo "Using $CCPATH to compile Cntlm"
    [ -h Makefile ] && rm -f Makefile 2>/dev/null
    case "$CC" in
        gcc)
            # default Makefile is for GCC; just revert back to
            # GCC if Makefile is linked to other compiler version
            if [ ! -f Makefile ]; then
                mv Makefile.gcc Makefile
            fi
            ;;
        *)
            # backup default GCC Makefile and create a link to other
            if [ -f Makefile ]; then
                mv Makefile Makefile.gcc
            fi

            EXT=`echo "$CC" | sed 's/_.*//'`
            ln -s Makefile.$EXT Makefile
            ;;
    esac
fi

STAMP=configure-stamp
CONFIG=config.h
TESTS="big_endian have_strdup have_socklen_t have_gethostname"

#[ -f $STAMP ] && exit 0
touch $STAMP

rm -f $CONFIG
for test_name in $TESTS; do
    test_name_uc=$(tr a-z A-Z<<<${test_name})

    printf "Checking ${test_name} ... "

    result=false
    if OUT=$($CC -D_POSIX_C_SOURCE=199506L -D_ISOC99_SOURCE -D_REENTRANT -o config/${test_name} config/${test_name}.c 2>&1) ; then
        if OUT=$(./config/${test_name}) ; then
            echo "yes"
            result=true
        else
            echo "no"
        fi
    else
        echo "no"
        echo "$OUT"
    fi

    if $result ; then
        echo "#define ${test_name_uc}" >>$CONFIG
    else
        echo "/* #undef ${test_name_uc} */" >>$CONFIG
    fi
done

while [ "$1" ]
do
    case "$1" in
        --enable-kerberos)
            printf "#define ENABLE_KERBEROS" >> $CONFIG
            ;;
        *)
            echo "Unknown flag $1"
            rm -f $CONFIG
            ;;
    esac
    shift
done