#!/bin/sh
#
# usage: $1 is featurename, $2 verbose 
# $3..$n librarynames like '-llibmysqlclient.*' or (optional) extra library paths like '-L/usr/local/lib'
# or filenames like "mysql.h" and (optional) extra include paths like '-I/usr/local/include'
# returns 0 on success

SUCCESS=
MODULE_NAME=$1
VERBOSE=$2
shift 2
LIBDIRS="/lib /usr/lib"
LIBNAMES=""
INCLUDEDIRS="/usr/include"
INCLUDES=""

PARAMS=$@
for PARAM in $PARAMS
do
    PREFIX=`echo $PARAM | sed 's/^\(..\).*/\1/'`
    case $PREFIX in
    -L)
	CLIBDIR=`echo $PARAM | sed -e 's/^-L//'`
	LIBDIRS="$LIBDIRS $CLIBDIR"
	;;
    -l)
	CLIBNAME=`echo $PARAM | sed -e 's/^-l//'`
	LIBNAMES="$LIBNAMES lib${CLIBNAME}.*"
	;;
    -I)
        CINCDIR=`echo $PARAM | sed -e 's/^-I//'`
        INCLUDEDIRS="$INCLUDEDIRS $CINCDIR"
        ;;
    *)
	INCLUDES="$PARAM $INCLUDES"
	;;
    esac 
done

# debuggery

if [ "$VERBOSE" = "yes" ]
then
    echo "$MODULE_NAME auto-detection..."
#    echo "searching for $LIBNAMES in $LIBDIRS"
#    echo "and $INCLUDES in $INCLUDEDIRS"
fi


# check for lib
for LIBNAME in $LIBNAMES
do
    SUCCESS=""
    for LIBDIR in $LIBDIRS
    do
	FOUND_LIB=`ls $LIBDIR/$LIBNAME 2>/dev/null`
	if [ ! -z "$FOUND_LIB" ]
	then
	    SUCCESS=yes
	    if [ "$VERBOSE" = "yes" ]
	    then
		echo "  Found $LIBNAME in $LIBDIR"
	    fi
	    break
	fi
    done
    if [ -z "$SUCCESS" ]
    then
	SUCCESS=no
	if [ "$VERBOSE" = "yes" ]
	then
	    echo "  Could not find $LIBNAME anywhere in $LIBDIRS"
	fi
	break
    fi
done

# check for includes
if [ "$SUCCESS" = "yes" ]
then
    for INCLUDE in $INCLUDES
    do
	SUCCESS=""
	for INCLUDEDIR in $INCLUDEDIRS
	do
	    FOUND_INC=`ls $INCLUDEDIR/$INCLUDE 2>/dev/null`
	    if [ ! -z "$FOUND_INC" ]
	    then
		SUCCESS=yes
		if [ "$VERBOSE" = "yes" ]
		then
		    echo "  Found $INCLUDE in $INCLUDEDIR"
		fi
		break
	    fi
	done
	if [ -z "$SUCCESS" ]
	then
	    SUCCESS=no
	    if [ "$VERBOSE" = "yes" ]
	    then
		echo "  Could not find $INCLUDE anywhere in $INCLUDEDIRS"
	    fi
	    break
	fi
    done
fi

if [ "$SUCCESS" != "yes" ]
then
    if [ "$VERBOSE" = "yes" ]
    then
	echo "$MODULE_NAME disabled."
    fi
    exit 1
else
    if [ "$VERBOSE" = "yes" ]
    then
        echo "$MODULE_NAME enabled."
    fi
    exit 0 
fi
exit 1

