#
# $Id: makl_libdep,v 1.19 2006/07/11 18:02:42 stewy Exp $
#

##\brief Evaluate the dependency
##
##  Evaluate a library dependency \e $1, given a base directory
##  \e $2, test file \e $3 and flags \e $4, \e $5.
##  If no flags are specified, the id is used as a library name
##  for linking. 
##  On success, HAVE_$1, HAVE_$1_CFLAGS and HAVE_$1_LDFLAGS are defined.
##
##   \param $1 id
##   \param $2 base directory ("" if not specified)
##   \param $3 CFLAGS 
##   \param $4 LDFLAGS
##   \return '0' on success, '1' on failure.
##
makl_libdep ()
{
    ID=`makl_upper $1`
    cwd=`pwd`
    tst=${makl_run_dir}/lib_testcode_$1.c
    if [ ! -r ${tst} ]; then
        tst=`pwd`/build/lib$1.c
        if [ ! -r ${tst} ]; then
            makl_warn "makl_libdep: no test file for $1 (${tst})!" 
            return 2
        fi
    fi

    [ -z "$3" ] && [ ! "$3" = "" ] || iflags="$3"
    [ -z "$2" ] || iflags="${iflags} -I$2/include" 

    [ -z "$2" ] || ldflags="-L$2/lib"
    if [ -z "$4" ]; then 
        ldflags="${ldflags} -l$1"
    else
        ldflags="${ldflags} $4"
    fi
    
    # compile and link the test program
    if [ -z `makl_get "__verbose__"` ]; then
        eval makl_compile ${tst} "${iflags}" "${ldflags}" 1> /dev/null \
                          2> /dev/null
    else 
        eval makl_compile ${tst} "${iflags}" "${ldflags}" 
    fi

    if [ $? -ne 0 ]; then
        makl_unset_var "HAVE_LIB${ID}"
        return 1
    fi

    # skip execution on cross-compilation
    if [ -z `makl_get "__cross_compile__"` ]; then
        cd ${makl_run_dir} && eval ./out > /dev/null 2> /dev/null
        if [ $? -ne 0 ]; then
            makl_dbg "Test file execution for lib$1 failed!"
            cd ${cwd}
            makl_unset_var "HAVE_LIB${ID}"
            return 2 
        fi
    fi

    # set LIBID_CFLAGS and LIBID_LDADD in Makefile.conf
    makl_set_var_mk "LIB${ID}_CFLAGS" "${iflags}"
    makl_set_var_mk "LIB${ID}_LDFLAGS" "${ldflags}"

    # set HAVE_LIBID in Makefile.conf and conf.h 
    makl_set_var "HAVE_LIB${ID}"

    cd ${cwd}
    return 0
}
