#!/bin/bash -e

TARGET="conf/config.in"
CHECK_FOR="sys/capability.h:lcap valgrind/memcheck.h ares.h:lcares"

_print_start() {
    echo -n "$1... "
}
_print_end_ok() {
    echo "OK"
}
_print_end_fail() {
    echo "FAIL"
}

_check_include() {
    if [ -n "$1" ]; then
        echo "#include <$1>" | g++ -E - &>/dev/null
    else
        echo "" | g++ -E - &>/dev/null
    fi
}

_check() {
    _print_start "Checking for '$1'"
    local DEF=`tr -c 'A-Z\n' '_' <<<"${1^^}"`
    if _check_include "$1"; then
        _print_end_ok
        echo "#define HAVE_$DEF 1" >> "$TARGET"
        return 0
    else
        _print_end_fail
        echo "#define HAVE_$DEF 0" >> "$TARGET"
        return 1
    fi
}

_print_start "Selftest"
if ! _check_include ""; then
    _print_end_fail
    exit 1
fi
if _check_include "nope"; then
    _print_end_fail
    exit 1
fi
_print_end_ok

_print_start "Creating '$TARGET'"
echo "/* created by the custom configure script. edit this file manually if needed or run it again. */" > "$TARGET"
_print_end_ok

HAVE_LFLAGS=""
for C in $CHECK_FOR; do
    if _check "${C%%:*}"; then
        if [ "${C##*:}" != "${C}" ]; then
            HAVE_LFLAGS+="-${C##*:} "
        fi
    fi
done
echo "//EXTRA_LFLAGS: $HAVE_LFLAGS" >> "$TARGET"

echo "DONE"