cat > configure.ac <<EOF
AC_PREREQ([2.61])

AC_INIT([FOO], [FOO_VERSION], [http://example.net/tracker/foo])

AC_CONFIG_HEADERS([config.h])
AC_PROG_CC

AC_ARG_WITH(
    [threads],
    [AS_HELP_STRING([--with(out)-threads@<:@=DIRECTORY@:>@],[disable/enable thread support])],
    ,
    [with_threads=yes]
)

# only check for sem_xxx if thread support is requested
if test x$with_threads != xno; then
    AC_SEARCH_LIBS([sem_init],[pthread rt posix4]) # 'Real Time' functions on Solaris
						   # posix4 on Solaris 2.6
						   # pthread (first!) on Linux
    AC_CHECK_HEADERS([semaphore.h])
    AC_CHECK_FUNCS([sem_open])
    AC_CHECK_FUNCS([sem_timedwait])
fi

###
AC_MSG_CHECKING([for sem_open XXX])
AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
    [[#include <semaphore.h>]],
    [[void *x=sem_open]])
],[
    AC_DEFINE([HAVE_SEM_OPEN_XXX], [1], [Define if you have the 'sem_open' function])
    AC_MSG_RESULT([yes])
],[
    AC_DEFINE([HAVE_SEM_OPEN_XXX], [0])
    AC_MSG_RESULT([no])
])
###
AC_MSG_CHECKING(for sem_open YYY)
AC_TRY_COMPILE([#include <semaphore.h>], void *x=sem_open,
  AC_DEFINE(HAVE_SEM_OPEN_YYY, 1, Define if you have the 'sem_open' function.)
  AC_MSG_RESULT(yes),
  AC_DEFINE(HAVE_SEM_OPEN_YYY, 0)
  AC_MSG_RESULT(no)
)
###

AC_OUTPUT([Makefile])
EOF


cat > foo.h <<EOF
#ifdef HAVE_SEMAPHORE_H
#  include <semaphore.h>
#endif
#ifdef HAVE_SEM_OPEN
  typedef sem_t *SEM_HANDLE;
#endif
EOF


cat > foo.c <<EOF
#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif
#include "foo.h"

/* ensure that after preprocessing this file is never empty */
typedef int foo_unused;
EOF


cat > Makefile.in <<EOF
OBJEXT = @OBJEXT@
all: foo.\$(OBJEXT)
EOF


rm -f configure
autoheader
autoconf
./configure
make
grep HAVE_ config.h
