#!/bin/sh

############################################################
# Copyright (c) 2009-2010 by Aleksey Cheusov
#
# See LICENSE file in the distribution.
############################################################

set -e

LC_ALL=C
export LC_ALL

: ${CHECK_COMMON_SH_DIR:=@mkc_libexecdir@}

##################################################
# options
usage (){
    cat <<EOF
mkc_check_funclib detects presense of function in a library
by compiling and linking a test program.

Usage: mkc_check_funclib [OPTIONS] function [libraries...]

OPTIONS:
   -h             display this help
   -d             delete cache files

Examples:
   mkc_check_funclib dlopen dl
   mkc_check_funclib dlopen
   mkc_check_funclib strlcpy
   mkc_check_funclib select socket
EOF
}

if test $# -eq 0; then
    usage
    exit 1
fi
if test "_$1" = '_-h'; then
    usage
    exit 0
fi
if test "_$1" = '_-d'; then
    delcache=1
    shift
fi

##################################################
# initializing

pathpart=funclib_`echo $* | tr '/. ' ___`

funcname=$1
shift

. ${CHECK_COMMON_SH_DIR}/mkc_check_common.sh

for i in "$@"; do
    LDADD="$LDADD -l$i"
    libs_msg="$libs_msg -l$i"
done

if test -n "$libs_msg"; then
    libs_msg=" ($libs_msg )"
fi

##################################################
# test

check_itself (){
    # preparations
    fname="$funcname"

    cat > "$tmpc" <<EOF
void yylex ();
void yylex () {}

int $fname (int, char **);

int main(int argc, char **argv)
{
   if (argc && argv) return 0;
   return $fname(0, (char*)0);
}
EOF

    # test itself
    if $CC -o "$tmpexe" "$tmpc" $LDFLAGS $LDADD 2>"$tmperr"; then
	echo 1
    else
	# SunPro may leave object files in current directory.
	# We need not this garbage. Also we cannot use smart shell
	# expansions because of crappy Solaris' /bin/sh.
	tmpbase=`basename "$tmpc" | sed 's/[.][^.]*$//'`
	rm -f ${tmpbase}.o
	echo 0
    fi
}

check_and_cache "checking for function implementation ${funcname}${libs_msg}" "$cache" "$@"

##################################################
# clean-ups

cleanup

##################################################
# finishing

if test "$ret" -eq 1; then
    printme 'yes\n' 1>&2
else
    printme 'no\n' 1>&2
fi

echo $ret
