#! /bin/sh

# $Id$

#######################################################################
# Constants:
cppo_version=0.9.4

# Helpers:

# Split $PATH into words:
oldifs="$IFS"
IFS="   :"
spacepath=`echo $PATH`
IFS="$oldifs"


in_path () {
    # Does $1 exist in $PATH?
    for d in $spacepath; do
        if test -x "$d/$1"; then
            return 0
        fi
    done
    return 1
}


get_path () {
    for d in $spacepath; do
        if test -x "$d/$1"; then
            echo "$d/$1"
            return
        fi
    done
}
#######################################################################
# Defaults

#--- Options ---
# value 0: off
# value 1: on
# defaults:

set_defaults () {
    enable_gtk=0
    enable_gtk2=0
    enable_tcl=0
    enable_zip=0
    enable_apache=0
    enable_gnutls=0
    enable_gssapi=0
    enable_pcre=0
    enable_full_pcre=0
    compat_pcre=0
    enable_nethttpd=0
    bindir=`dirname "$ocamlc"`
    tcl_defs=""
    tcl_libs=""
    disable_core=0
    apxs=""
    apache=""
    cpp=cpp
    cpp_set=0
    gnutls_cflags=""
    gnutls_libs=""
    gnutls_system_trust_file=""
    gssapi_cflags=""
    gssapi_libs=""
    destdir=""
}

ocamlc=`get_path ocamlc`
set_defaults

version="4.1.2"
exec_suffix=""
path_sep=":"

#######################################################################
# Option parsing

ehelp_gtk="Enable/disable parts that depend on lablgtk"
ehelp_gtk2="Enable/disable parts that depend on lablgtk2"
ehelp_tcl="Enable/disable parts that depend on tcl/tk"
ehelp_gnutls="Enable/disable parts that depend on GnuTLS"
ehelp_gssapi="Enable/disable parts that depend on GSSAPI/Kerberos"
ehelp_zip="Enable/disable parts that depend on camlzip"
ehelp_apache="Enable/disable Apache mod connector (EXPERIMENTAL)"
ehelp_pcre="Enable/disable the build against pcre-ocaml"
ehelp_full_pcre="Enable/disable the build against pcre-ocaml (no Str)"
ehelp_nethttpd="Enable/disable nethttpd web server component (GPL!)"

# Which options exist? eoptions for enable/disable
eoptions="pcre full_pcre gtk gtk2 tcl gnutls gssapi zip apache nethttpd"

# Packages to include anyway:
requires="bytes unix"

# Directory where to install data files:
net_db_dir="<library directory>"
net_db_dir_set=0

check_library () {
    # $1: the name of the library (findlib)
#   # $2: a typical file in $incdirs
#    if [ "$enable_findlib" -gt 0 ]; then
	ocamlfind query "$1" >/dev/null 2>/dev/null
	return
#    else
#	stdlib=`ocamlc -where`
#	for dir in $incdirs; do
#	    case "$dir" in
#		+*)
#		    dir=`echo "$dir" | sed -e "s|^\+|$stdlib/|"` ;;
#	    esac
#	    if [ -f "$dir/$2" ]; then
#		return 0
#	    fi 
#	done
	return 1   # not found
#    fi
}


print_options () {
	for opt in $eoptions; do
		e="o=\$enable_$opt"
		eval "$e"
		uopt=`echo $opt | sed -e 's/_/-/g'`
		if [ $o -gt 0 ]; then
			echo "    -enable-$uopt"
		else
			echo "    -disable-$uopt"
		fi
	done
	echo "    -bindir $bindir"
	echo "    -datadir $net_db_dir"
	if [ $enable_tcl -gt 0 ]; then
            echo "    -equeue-tcl-defs \"$tcl_defs\""
            echo "    -equeue-tcl-libs \"$tcl_libs\""
	fi
	if [ -n "$apxs" ]; then
	    echo "    -apxs $apxs"
	fi
	if [ -n "$apache" ]; then
	    echo "    -apache $apache"
	fi
        if [ -n "$gnutls_cflags" ]; then
            echo "    -gnutls-cflags $gnutls_cflags"
        fi
        if [ -n "$gnutls_libs" ]; then
            echo "    -gnutls-libs $gnutls_libs"
        fi
        if [ -n "$gnutls_system_trust_file" ]; then
            echo "    -gnutls-system-trust-file $gnutls_system_trust_file"
        fi
        if [ -n "$gssapi_cflags" ]; then
            echo "    -gssapi-cflags $gssapi_cflags"
        fi
        if [ -n "$gssapi_libs" ]; then
            echo "    -gssapi-libs $gssapi_libs"
        fi
        echo "    -cpp $cpp"
}


usage () {
	set_defaults
	cat <<_EOF_ >&2
usage: ./configure [ options ]

_EOF_
	for opt in $eoptions; do
		e="help=\$ehelp_$opt"
		eval "$e"
		uopt=`echo $opt | sed -e 's/_/-/g'`
		echo "-enable-$uopt:" >&2
		echo "-disable-$uopt:" >&2
		echo "        $help" >&2
	done
	cat <<_EOF_ >&2
-bindir dir
        Install binaries into this directory

-datadir dir
        Install the run-time data file into this directory

-equeue-tcl-defs <opts>
        Set C compiler options to find tcl.h (for -enable-tcl)

-equeue-tcl-libs <opts>
        Set C compiler options to link against libtcl (for -enable-tcl)

-apxs /path/to/apxs
        Set which apxs to use for -enable-apache

-apache /path/to/apache
        Set which apache executable to use for -enable-apache

-gnutls-cflags <opts>
        Flags for the C compiler for GnuTLS

-gnutls-libs <opts>
        Libraries for GnuTLS

-gnutls-system-trust-file /path/to/certificates.crt
        File with the certificates that are trusted by default

-gssapi-cflags <opts>
        Flags for the C compiler for GSSAPI

-gssapi-libs <opts>
        Libraries for GSSAPI

-prefer-netcgi2
        This option is ignored for compatibility with older versions

-cpp <path>
        Use this C preprocessor program for ocamlrpcgen

-compat-pcre
        Makes the netstring library dependent on netstring-pcre, for
        better compatibility with old versions of Ocamlnet

Defaults are:

_EOF_
	print_options >&2
	exit 1
}


check_eopt () {
	for x in $eoptions; do
		if [ "$x" = "$1" ]; then
			return 0
		fi
	done
	echo "Unknown option: $1" >&2
	exit 1
}


echo "Welcome to Ocamlnet version $version" >&2

while [ "$#" -gt 0 ]; do
	case "$1" in
		-enable-*|--enable-*)
			opt=`echo "$1" | sed -e 's/--\{0,1\}enable-//' -e 's/-/_/g'`
			check_eopt "$opt"
			eval "enable_$opt=2"
			shift
			;;
	        -disable-core|--disable-core)
		        # Intentionally undocumented.
		        disable_core=1
			shift
			;;
		-disable-*|--disable-*)
			opt=`echo "$1" | sed -e 's/--\{0,1\}disable-//' -e 's/-/_/g'`
			check_eopt "$opt"
			eval "enable_$opt=-1"
			shift
			;;
		-with-*|--with*)
			opt=`echo "$1" | sed -e 's/--\{0,1\}with-//' -e 's/-/_/g'`
			check_eopt "$opt"
			eval "enable_$opt=2"
			shift
			;;
		-without-*|--without*)
			opt=`echo "$1" | sed -e 's/--\{0,1\}without-//' -e 's/-/_/g'`
			check_eopt "$opt"
			eval "enable_$opt=-1"
			shift
			;;
                -prefix|--prefix)
                        bindir="$2/bin"; shift 2 ;;
                --prefix=*)
                        p=`echo "$1" | set -e 's/--prefix=//'`
                        bindir="$p/bin"; shift ;;
                -bindir|--bindir)
                        bindir="$2"
                        shift
                        shift
                        ;;
                --bindir=*)
                        bindir=`echo "$1" | set -e 's/--bindir=//'`
                        shift
                        ;;
	        -datadir|--datadir)
		        net_db_dir="$2"
			net_db_dir_set=1
			shift; shift
			;;
	        --datadir=*)
		        net_db_dir=`echo "$1" | set -e 's/--datadir=//'`
			net_db_dir_set=1
			shift
			;;
                -equeue-tcl-defs|--equeue-tcl-defs)
                        tcl_defs="$tcl_defs $2"
                        shift
                        shift
                        ;;
                --equeue-tcl-defs=*)
                        tcl_defs=`echo "$1" | set -e 's/--equeue-tcl-defs=//'`" $2"
                        shift
                        ;;
                -equeue-tcl-libs|--equeue-tcl-libs)
                        tcl_libs="$tcl_libs $2"
                        shift
                        shift
                        ;;
                --equeue-tcl-libs=*)
                        tcl_libs=`echo "$1" | set -e 's/--equeue-tcl-libs=//'`" $2"
                        shift
                        ;;
                -apxs|--apxs)
                        apxs="$2"
                        shift
                        shift
                        ;;
                --apxs=*)
                        apxs=`echo "$1" | set -e 's/--apxs=//'`
                        shift
                        ;;
                -apache|--apache)
                        apache="$2"
                        shift
                        shift
                        ;;
                --apache=*)
                        apache=`echo "$1" | set -e 's/--apache=//'`
                        shift
                        ;;
                -gnutls-cflags|--gnutls-cflags)
                        gnutls_cflags="$2"
                        shift
                        shift
                        ;;
                --gnutls-cflags=*)
                        gnutls_cflags=`echo "$1" | set -e 's/--gnutls-cflags=//'`
                        shift
                        ;;
                -gnutls-libs|--gnutls-libs)
                        gnutls_libs="$2"
                        shift
                        shift
                        ;;
                --gnutls-libs=*)
                        gnutls_libs=`echo "$1" | set -e 's/--gnutls-libs=//'`
                        shift
                        ;;
                -gnutls-system-trust-file|--gnutls-system-trust-file)
                        gnutls_system_trust_file="$2"
                        shift 2
                        ;;
                --gnutls-system-trust-file=*)
                        gnutls_system_trust_file=`echo "$1" | set -e 's/--gnutls-system-trust-file=//'`
                        shift
                        ;;
                -gssapi-cflags|--gssapi-cflags)
                        gssapi_cflags="$2"
                        shift
                        shift
                        ;;
                --gssapi-cflags=*)
                        gssapi_cflags=`echo "$1" | set -e 's/--gssapi-cflags=//'`
                        shift
                        ;;
                -gssapi-libs|--gssapi-libs)
                        gssapi_libs="$2"
                        shift
                        shift
                        ;;
                --gssapi-libs=*)
                        gssapi_libs=`echo "$1" | set -e 's/--gssapi-libs=//'`
                        shift
                        ;;
	        -prefer-netcgi2|--prefer-netcgi2)
		        # ignore!
			shift ;;
                -cpp|--cpp)
                        cpp="$2"
                        cpp_set=1
                        shift
                        shift
                        ;;
                --cpp=*)
                        cpp=`echo "$1" | set -e 's/--cpp=//'`
                        cpp_set=1
                        shift
                        ;;
		-version|--version)
			echo "$version"
			exit 0
			;;
                -compat-pcre|--compat-pcre)
                        compat_pcre=1
                        shift ;;
                -destdir|--destdir)
                        destdir="$2"; shift 2;;
                --destdir=*)
                        destdir=`echo "$1" | set -e 's/--destdir=//'`; shift;;
		*)
			usage
	esac
done


######################################################################
# cleanup

rm -f config.cppo

######################################################################
# Check OS

with_rpc_xti=0
with_cppo_tweak=0
printf "%s" "Checking operating system... "
u=`uname`
case "$u" in
	CYGWIN*)
		printf "Cygwin, and target is: "
		exec_suffix=".exe"
		path_sep=";"   # this is only for OCAMLPATH, ";" is correct for Cygwin
		case `ocamlc -config | grep os_type` in
		    *Win32*)
                        with_cppo_tweak=1
                        if [ $cpp_set = 0 ]; then
                            cpp=`realpath /bin/cpp | cygpath -m -f -`
                        fi
			echo "Win32" ;;
		    *)
			echo "Cygwin" ;;
		esac
		;;
        MINGW*)
		echo "MinGW"
		exec_suffix=".exe"
		with_cppo_tweak=2
		path_sep=";"
		mingw_lib=`get_path gcc`
		mingw_lib=`dirname "$mingw_lib"`/../lib
		OCAMLOPTFLAGS="-ccopt -L\"${mingw_lib}\""
		;;
        Linux)
	        echo "Linux"
		;;
        *FreeBSD)             # also GNU/kFreeBSD
	        echo "FreeBSD"
		echo
		echo "*** Note that you might need to load the 'sem' kernel"
		echo "*** module to make semaphores work: kldload sem"
		echo
		;;
        NetBSD)
	        echo "NetBSD"
		;;
        SunOS)
	        case `uname -r` in
		    [1234]*)
		        echo "SunOS" ;;
		    *)
			echo "Solaris"
			with_rpc_xti=1
			;;
		esac ;;
	*)
		echo "Generic" ;;
esac

if [ $with_rpc_xti -gt 0 ]; then
    echo "    This OS supports XTI networking"
    echo "    Building rpc-xti"
fi

######################################################################
# Check ocamlfind

printf "%s" "Checking for findlib... "
if ocamlfind query stdlib >/dev/null 2>/dev/null; then
    echo "found"
    if [ "$net_db_dir_set" -eq 0 ]; then
	net_db_dir=`ocamlfind printconf destdir | tr -d '\\r'`/netunidata
	net_db_dir_set=1
    fi
else
    echo "not found"
    echo "Make sure that ocamlfind is in your PATH, or download findlib"
    echo "from www.ocaml-programming.de"
    exit 1
fi

if [ "$net_db_dir_set" -eq 0 ]; then
    net_db_dir="$libdir"
    net_db_dir_set=1
fi

######################################################################
# Does ocamlopt support multi-threading?

printf "%s" "Checking multi-threading support... "
mt_type=vm
mt_switch="-vmthread"
mt_comment="(unsupported)"
rm -rf tmp
mkdir -p tmp
cat <<_EOF_ >tmp/t.ml
let _ = Mutex.create();;
_EOF_
if ocamlopt -thread -o tmp/t${exec_suffix} ${OCAMLOPTFLAGS} unix.cmxa threads.cmxa tmp/t.ml 2>/dev/null ||
    ocamlc -thread -o tmp/t${exec_suffix} unix.cma threads.cma tmp/t.ml 2>/dev/null; then
    if tmp/t${exec_suffix} 2>/dev/null; then
	mt_type=posix
	mt_switch="-thread"
	mt_comment="(ok)"
    fi
fi
echo "$mt_type $mt_comment"

######################################################################
# Check word size at al

printf "%s" "Checking word size... "
cat <<_EOF_ >tmp/t.ml
print_endline(string_of_int(Sys.word_size))
_EOF_
word_size="$(ocaml tmp/t.ml | tr -d '\r')"
echo "$word_size bit"

printf "%s" "Checking endianess... "
cat <<_EOF_ >tmp/tend.c
/* new check from Matías Giovannini */
#include "caml/mlvalues.h"
value check(value d) {
  int i = 1;
  char *s = (char*) &i;
  return (s[0] == 0 ? Val_true : Val_false);
}
_EOF_

cat <<_EOF_ >tmp/t.ml
external check : unit -> bool = "check";;

let () =
  exit (if check() then 0 else 1)
_EOF_

( cd tmp
  ocamlc -custom -o t tend.c t.ml
) || exit

if tmp/t; then
    echo "big"
    endianess="BIG_ENDIAN"
else
    echo "little"
    endianess="LITTLE_ENDIAN"
fi

######################################################################

printf "Checking for GPROF... "

stdlib=`ocamlc -where | tr -d '\r'`
if [ -f $stdlib/std_exit.p.cmx ]; then
    echo "found"
    have_gprof=1
else
    echo "not found"
    have_gprof=0
fi

######################################################################

printf "Checking for attributes... "
case `ocamlc -version` in
  [123].*)
        echo "no"
        attrs=0 ;;
  4.0[01].*)
        echo "no"
        attrs=0 ;;
  *)
        echo "yes"
        attrs=1 ;;
esac

if [ $attrs -gt 0 ]; then
    cat <<EOF >>config.cppo
#define DEPRECATED(arg) [@@deprecated arg] \(** @deprecated arg *)
EOF
else
    cat <<EOF >>config.cppo
#define DEPRECATED(arg)
EOF
fi

######################################################################

printf "Checking for immutable strings... "
if ocamlc -safe-string >/dev/null 2>/dev/null; then
    istring=1
    echo "yes"
else
    istring=0
    echo "no"
fi

if [ $istring -gt 0 ]; then
    string_opts="-safe-string"
    pp_bytes="-D HAVE_BYTES"
else
    string_opts=""
    pp_bytes="-U HAVE_BYTES"
fi

######################################################################

printf "Checking for extensible variants... "
cat <<EOF >tmp/extvariant.ml
type t = ..
type t += X
EOF

if ocamlc -c tmp/extvariant.ml >/dev/null 2>/dev/null; then
    echo "yes"
    echo "#define HAVE_EXTENSIBLE_VARIANTS" >> config.cppo
else
    echo "no"
    echo "#undef HAVE_EXTENSIBLE_VARIANTS" >> config.cppo
fi


######################################################################
# Check that pcre is available:

if [ $enable_pcre -gt 0 -o $enable_full_pcre -gt 0 ]; then
    printf "%s" "Checking for PCRE... "
    if check_library pcre pcre.cmi; then
	echo "found"
        # This means to build netstring-pcre
	have_pcre=1
        if [ $enable_full_pcre -gt 0 ]; then
            # In netstring: Netstring_str uses PCRE as backend
  	    regexp_defs="-D HAVE_PCRE"
	    regexp_provider="netstring-pcre"  # which again depends on pcre
            regexp_provider_make="pcre"       # also solved via -I to netstring-pcre
        else
            # In netstring: Netstring_str uses Str as backend
            regexp_defs="-D ENABLE_STR_EXTERNALS -D HAVE_PCRE"
            regexp_provider="str"
            regexp_provider_make="str"
        fi
    else
	echo "not found"
	echo "Sorry, PCRE was requested."
	echo "Get the PCRE-OCaml library from:"
	echo "http://www.ocaml.info/home/ocaml_sources.html,"
	echo "or disable the build against PCRE-Ocaml (not recommended)".
	exit 1
    fi
else
    # ENABLE_STR_EXTERNALS works for all recent OCaml versions
    have_pcre=0
    regexp_defs="-D ENABLE_STR_EXTERNALS"
    regexp_provider="str"
    regexp_provider_make="str"
fi

compat_pcre_provider=""
if [ $compat_pcre -gt 0 ]; then
    # in this case, netstring is dependent on netstring-pcre for
    # better compatibility with OCamlnet-3.5 and older. Even if we
    # did NOT -enable-pcre.
    compat_pcre_provider="netstring-pcre"
fi

######################################################################
# Netsys

( cd src/netsys; ./configure )

( cd src/rpc-auth-local; ./configure )

######################################################################
# whether we can support camlboxes and multicore

support_outofheap=0
if grep 'OOH_OBJECT = .' src/netsys/Makefile.conf >/dev/null 2>/dev/null; then
    support_outofheap=1
fi

support_semaphores=0
if grep '#define HAVE_POSIX_SEM_NAMED' src/netsys/config.h \
    >/dev/null 2>/dev/null; then
    support_semaphores=1
fi

enable_camlbox=0
enable_multicore=0
printf "Checking whether netcamlbox and netmulticore are supported... "
if [ $support_outofheap -gt 0 -a $support_semaphores -gt 0 ]; then
    echo "yes"
    enable_camlbox=1
    enable_multicore=1
else
    echo "no"
fi


######################################################################
# TCL

with_equeue_tcl=0

if [ $enable_tcl -gt 0 ]; then
    printf "%s" "Checking switches for tcl.h... "

    tcl_defs_1=""
    for d in $tcl_defs; do
        tcl_defs_1="$tcl_defs_1 -ccopt '$d'"
    done

    rm -rf tmp
    mkdir -p tmp

    cat <<EOF >tmp/t.c
#include "tcl.h"

main () {
}
EOF

    if ( cd tmp; ocamlc $tcl_defs_1 -c t.c >/dev/null 2>/dev/null ) then
        echo "ok"
    else
        echo "not ok"
        echo
        echo "Please check -equeue-tcl-defs!"
        exit 1
    fi

    printf "%s" "Checking switches to link libtcl... "

    cat <<EOF >tmp/t.c
#include <stdlib.h>
#include <stdio.h>
#include "tcl.h"

do_something () {
    void (*x)(int);
    x = Tcl_Exit;
    exit(0);
}
EOF

    cat <<EOF >tmp/t.ml
exit 0
EOF

    if ( cd tmp
         ocamlc $tcl_defs_1 -c t.c >/dev/null 2>/dev/null &&
         ocamlc -c t.ml >/dev/null 2>/dev/null &&
         ocamlc -o t -custom t.o t.cmo -cclib "$tcl_libs"
       )
    then
        if tmp/t; then
            echo "ok"
        else
            echo "not ok (check ldd output of tmp/t)"
            echo
            echo "Please check -equeue-tcl-libs!"
            exit 1
        fi
    else
        echo "not ok"
        echo
        echo "Please check -equeue-tcl-libs!"
        exit 1
    fi

    with_equeue_tcl=1
fi

######################################################################
# Check lablgtk

with_equeue_gtk1=0

if [ $enable_gtk -gt 0 ]; then
    printf "%s" "Checking for lablgtk... "
    if ocamlfind query lablgtk >/dev/null 2>/dev/null; then
        echo "found"
	with_equeue_gtk1=1
    else
        echo "not found"
	echo "Required library lablgtk not found!"
	exit 1
    fi
fi

######################################################################
# Check lablgtk2

with_equeue_gtk2=0
gtk2_io_add_watch_supports_lists=""

if [ $enable_gtk2 -gt 0 ]; then
    printf "%s" "Checking for lablgtk2... "
    if ocamlfind query lablgtk2 >/dev/null 2>/dev/null; then
        echo "found"
    else
        echo "not found"
	echo "Required library lablgtk2 not found!"
	exit 1
    fi

    printf "%s" "Checking whether lablgtk2 has GMain.Io.remove... "
    mkdir -p tmp
    cat <<EOF >tmp/gtktest.ml
let _ = GMain.Io.remove;;
EOF

    if ocamlfind ocamlc -package lablgtk2 -c tmp/gtktest.ml >/dev/null 2>/dev/null;
    then
        echo "yes"
    else
        echo "no"
        echo "Your version of lablgtk2 is too old!"
	exit 1
    fi
    
    printf "%s" "Checking whether lablgtk2 has GMain.Io.add_watch with list support... "
    mkdir -p tmp
    cat <<'EOF' >tmp/gtktest.ml
open GMain.Io
let _ = (add_watch : cond:condition list -> callback:(condition list -> bool) -> ?prio:int -> channel -> id);;
exit 0
EOF
    # Note: this newer API is never broken in the sense checked below, i.e.
    # such lablgtk2 versions do not exist.
    if ocamlfind ocamlc -package unix,lablgtk2 -linkpkg -o tmp/gtk tmp/gtktest.ml >/dev/null 2>/dev/null && tmp/gtk; then
        echo "yes"
        gtk2_io_add_watch_supports_lists="-D GTK2_IO_ADD_WATCH_SUPPORTS_LISTS"
    else
        echo "no"
        printf "%s" "Checking whether lablgtk2's GMain.Io.add_watch is broken... "
        mkdir -p tmp
        cat <<'EOF' >tmp/gtktest.ml
GMain.Main.init();;
let ch = GMain.Io.channel_of_descr (Unix.stdout) in
let w = GMain.Io.add_watch
          ~cond:`OUT ~callback:(fun () -> true) ch in
(* add_watch is broken when it just returns Val_unit, and ok when it
 * returns a positive int
 *)
if (Obj.magic w : int) > 0 then
  exit 0
else
  exit 1
EOF
	if ocamlfind ocamlc -package unix,lablgtk2 -linkpkg -o tmp/gtk tmp/gtktest.ml >/dev/null 2>/dev/null && tmp/gtk; then
            echo "no"
        else
            echo "yes"
            echo "You should apply the patch-ab-ml_glib.c to lablgtk2 to fix this!"
	    exit 1
        fi
    fi

    for f in Makefile uq_gtk.ml uq_gtk.mli uq_gtk_helper.ml; do
	rm -f src/equeue-gtk2/$f
	ln -s ../equeue-gtk1/$f src/equeue-gtk2
    done
    
    with_equeue_gtk2=1
fi

######################################################################
# GnuTLS

with_gnutls=0

if [ $enable_gnutls -gt 0 ]; then
    ( cd src/nettls-gnutls
      GNUTLS_CFLAGS="$gnutls_cflags" GNUTLS_LIBS="$gnutls_libs" GNUTLS_SYSTEM_TRUST_FILE="$gnutls_system_trust_file" ./configure
    )
    if [ $? -eq 0 ]; then
        with_gnutls=1
        # There is now also src/nettls-gnutls/config.mk, which needs to be
        # appended to Makefile.conf
    else
        echo "Required library GnuTLS not found!"
        exit 1
    fi
fi

######################################################################
# GSSAPI

with_gssapi=0

if [ $enable_gssapi -gt 0 ]; then
    ( cd src/netgss-system
      GSSAPI_CFLAGS="$gssapi_cflags" GSSAPI_LIBS="$gssapi_libs" ./configure
    )
    if [ $? -eq 0 ]; then
        with_gssapi=1
        # There is now also src/netgss-system/config.mk, which needs to be
        # appended to Makefile.conf
    else
        echo "Required library for GSSAPI (probably -lkrb5) not found!"
        exit 1
    fi
fi

######################################################################
# Check camlzip

with_netzip=0

if [ $enable_zip -gt 0 ]; then
    printf "%s" "Checking for zip/camlzip... "
    if ocamlfind query zip >/dev/null 2>/dev/null; then
        echo "found"
        with_netzip=1
        zip_provider=zip
    else
        if ocamlfind query camlzip >/dev/null 2>/dev/null; then
            echo "found"
	    with_netzip=1
	    zip_provider=camlzip
        else
            echo "not found"
	    echo "Required library camlzip not found!"
	    exit 1
        fi
    fi
fi

######################################################################
# Check Apache

apache_major=0   # otherwise syntax error
if [ $enable_apache -gt 0 ]; then
    printf "Apache mod connector... "

#     echo "CURRENTLY BROKEN - disabling for now"
#     enable_apache=0

    if [ -z "$apxs" ]; then
	# guess
	apxs=`get_path apxs`
    fi
    if [ -z "$apache" ]; then
	# guess
	apache=`get_path apache`
    fi

    if [ -x "$apxs" ] && [ -x "$apache" ]; then
	apache_major=`$apache -v | head -n1 | sed -e "s,.*/\([1-9]\).*,\1,"`
	apache_libdir="`$apxs -q LIBEXECDIR`"
	apache_incdir="`$apxs -q INCLUDEDIR`"
	apache_confdir="`$apxs -q SYSCONFDIR`"
	apache_ldflags_shlib="`$apxs -q LDFLAGS_SHLIB`"
	apache_cc="`$apxs -q CC`"
	apache_cflags="-I \$(APACHE_INCDIR) \
	  `$apxs -q CFLAGS` `$apxs -q CFLAGS_SHLIB`"
	# This is to allow modules residing in the standard  ocaml library 
	# directory to be loaded with relative paths.
	#apache_ocamllibdir=`ocamlfind printconf destdir`
	apache_ocamllibdir=`ocamlc -where`
	# The apache module requires the construction of a shared library
	# embedding the ocaml runtime.  On platforms where PIC code differs
	# from non-PIC, it requires a shared camlrun.  Check whether it is
	# available.  See http://caml.inria.fr/mantis/view.php?id=3866
	apache_camlrun=camlrun
	if [ -f "$apache_ocamllibdir/libcamlrun_shared.so" ]; then
	    apache_camlrun=camlrun_shared
	    echo "enabled (Apache $apache_major)"
	else
	    echo "enabled (Apache $apache_major)"
	    echo -e "    WARNING: libcamlrun_shared.so was not found.  That \
may prevent the build\n    of the apache module on platforms \
where PIC code differs from non-PIC\n    such as x86_64, hppa,..."
	fi
	# at some point libstr.a was renamed to libcamlstr.a
	libstr="str"
	if [ -f "$apache_ocamllibdir/libcamlstr.a" ]; then
	    libstr="camlstr"
	fi
    else
	enable_apache=0
	echo "apxs or apache not found"
	echo "    Maybe you need to use the -apache option?"
	exit 1
    fi

fi

######################################################################
# cpp

echo "Preprocessor for ocamlrpcgen: $cpp"

######################################################################
# Summary

echo
echo "Effective options:"
print_options
echo

pkglist="netsys netshm netstring netunidata equeue shell rpc-generator rpc rpc-auth-local netclient netcgi2 netplex netcgi2-plex"

full_pkglist="$pkglist netstring-pcre rpc-auth-local rpc-xti equeue-tcl equeue-gtk1 equeue-gtk2 nethttpd netzip netcgi2-apache nettls-gnutls netgss-system"

if [ $enable_camlbox -gt 0 ]; then
    pkglist="$pkglist netcamlbox"
fi

if [ $enable_multicore -gt 0 ]; then
    pkglist="$pkglist netmulticore"
fi

if [ $enable_nethttpd -gt 0 ]; then
    pkglist="$pkglist nethttpd"
fi

if [ $disable_core -gt 0 ]; then
    # Omit the core packages:
    pkglist=""
    with_rpc_xti=0
fi

for opt in rpc_xti $woptions equeue_tcl equeue_gtk1 equeue_gtk2 netzip; do
	e="o=\$with_$opt"
	eval "$e"
	if [ $o -gt 0 ]; then
		uopt=`echo "$opt" | sed -e 's/_/-/g'`
		pkglist="$pkglist $uopt"
	fi
done

if [ $enable_pcre -gt 0 -o $enable_full_pcre -gt 0 ]; then
    pkglist="netstring-pcre $pkglist"
fi

if [ $enable_apache -gt 0 ]; then
    pkglist="$pkglist netcgi2-apache"
fi

if [ $enable_gnutls -gt 0 ]; then
    pkglist="$pkglist nettls-gnutls"
fi

if [ $enable_gssapi -gt 0 ]; then
    pkglist="$pkglist netgss-system"
fi

######################################################################
# Write Makefile.conf

if [ $with_cppo_tweak -ne 0 ]; then
    # Under Windows, calling cppo by relative path is difficult. If we
    # use forward slashes, we need to escape these for cmd.exe. If we
    # use backward slashes, the escaping is difficult for sh+make.
    # The workaround is to call cppo implicitly by PATH search.
    xdir="$(readlink -f "$(dirname "$0")")"
    if [ $with_cppo_tweak -eq 1 ]; then
        xdir="$(cygpath "${xdir}")"
    fi
    xdir="${xdir}/tools/cppo-${cppo_version}"
    export_path="export PATH:=${xdir}:\$(PATH)"
    cppo="cppo-ocamlnet.exe"
else
    export_path=""
    cppo="\$(TOP_DIR)/tools/cppo-${cppo_version}/cppo"
fi

echo "Writing Makefile.conf"
cat <<_EOF_ >Makefile.conf
# Makefike.conf written by configure
# The Ocamlnet version
VERSION = $version

# The packages to build in the right order:
PKGLIST = $pkglist

# All packages:
FULL_PKGLIST = $full_pkglist

# Whether the OS needs an .exe suffix for executables:
EXEC_SUFFIX = $exec_suffix
PATH_SEP = $path_sep

# Required packages (findlib):
REQUIRES += $requires

# zip:
ZIP_PROVIDER = $zip_provider

# Additional options only for ocamlc:
OCAMLC_OPTIONS =

# Additional options only for ocamlopt:
OCAMLOPT_OPTIONS =

# Where the ocamlnet lookup tables are to be installed (both findlib
# and non-findlib):
NET_DB_DIR = $net_db_dir

# Where binaries are installed:
BINDIR = $bindir

# Method of installation:
INSTMETHOD = findlib

# Multi-threading type:
MT_TYPE = $mt_type

# word size:
WORD_SIZE = $word_size

# endianess
ENDIANESS = $endianess

# gprof:
HAVE_GPROF = $have_gprof

# definition of the DEPRECATED macro
PP_DEPRECATED =

# strings
STRING_OPTS = $string_opts
PP_BYTES = $pp_bytes

# REGEXP support:
REGEXP_DEFS = $regexp_defs
HAVE_PCRE = $have_pcre
REGEXP_PROVIDER = $regexp_provider
REGEXP_PROVIDER_MAKE = $regexp_provider_make
COMPAT_PCRE_PROVIDER = $compat_pcre_provider

# Compiler switch to enable multi-threading:
THREAD = $mt_switch

# For -enable-tcl:
EQUEUE_TCL_DEFS = $tcl_defs_1
EQUEUE_TCL_LIBS = $tcl_libs

# For -enable-gtk2:
GTK_EXTRA_DEFINES = $gtk2_io_add_watch_supports_lists

# For -enable-apache
APACHE_MAJOR = $apache_major
APACHE_LIBDIR = $apache_libdir
APACHE_OCAMLLIBS = -l$apache_camlrun -ltermcap -lunix -l$libstr
APACHE_INCDIR = $apache_incdir
APACHE_CONFDIR = $apache_confdir
APACHE_LDFLAGS_SHLIB = $apache_ldflags_shlib
APACHE_CC = $apache_cc
APACHE_CFLAGS = $apache_cflags
APACHE_OCAMLLIBDIR = $apache_ocamllibdir
APXS = $apxs

# ocamlrpcgen
OCAMLRPCGEN_CPP = $cpp

# cppo:
CPPO = $cppo -include \$(TOP_DIR)/config.cppo
CPPO_VERSION = $cppo_version
$export_path
_EOF_

if [ $with_gnutls -gt 0 ]; then
    cat src/nettls-gnutls/config.mk >>Makefile.conf
fi

if [ $with_gssapi -gt 0 ]; then
    cat src/netgss-system/config.mk >>Makefile.conf
fi

if [ -n "$destdir" ]; then
    echo "DESTDIR = $destdir" >>Makefile.conf
fi

rm -f src/netcgi2-apache/config.h

######################################################################
# make oasis happy: setup.save will be picked up by "make postconf"
# and will be appended to setup.data. That way the config update
# will reach oasis.

rm -f setup.save
echo "pkg_version=\"$version\"" >>setup.save
echo "bindir= \"$bindir\"" >>setup.save
echo "datadir=\"$net_db_dir\"" >>setup.save
echo "prefix=\"<not interpreted>\"" >>setup.save
echo "destdir=\"$destdir\"" >>setup.save

for opt in $eoptions; do
    e="o=\$enable_$opt"
    eval "$e"
    if [ $o -gt 0 ]; then
        echo "$opt=\"true\"" >>setup.save
    else
        echo "$opt=\"false\"" >>setup.save
    fi
done

######################################################################
# Finish

echo
echo "Please check Makefile.conf."
echo
echo "You can now compile Ocamlnet by invoking"
echo "   make all"
echo "for the bytecode compiler, and optionally by invoking"
echo "   make opt"
echo "for the native-code compiler (if supported on your architecture)."
echo "Finally, a"
echo "   make install"
echo "will install the package(s)."
