dnl This file is in the public domain.

dnl Process this file with Autoconf to produce a configure script.

dnl Remove the datarootdir/docdir tests below if this is increased:
AC_PREREQ([2.59])
AC_INIT([darcs], [1.1.0pre1], [bugs@darcs.net])
AC_CONFIG_SRCDIR([src/darcs.lhs])

dnl Write our invocation date/time and flags into a file so that
dnl Darcs knows how it was built.

ac_cmdline_args="$*"
AC_CONFIG_COMMANDS([config.command],
                   [ echo > config.command "# configured $date"
                     echo >>config.command "./configure $args"
		     chmod +x config.command
                   ],
                   [date="`date`"; args="$ac_cmdline_args"])

dnl The following is now the authoritative location of the version
dnl number. All references to the darcs version number should
dnl originate here. From Haskell this is easily done by importing
dnl the module "Autoconf ( darcs_version )".
dnl
dnl The version string must not contain any spaces. The version
dnl state will automatically be set to any of:
dnl
dnl    "prerelease #n"
dnl    "release candidate #n"
dnl    "release"
dnl    "unstable branch"
dnl    "stable branch"
dnl    "unknown branch"
dnl
dnl The new darcs custom is to increase the version number
dnl directly after a release, since the checking for a tag
dnl indicates whether the number is really correct.

DARCS_VERSION=$PACKAGE_VERSION

dnl See if we are in a darcs repo and also have darcs available,
dnl in which case we can try to figure out the release state:

AC_CHECK_PROG(DARCS, darcs, darcs)
AC_MSG_CHECKING([the release state])
if test ! -z "$DARCS" && test -d "_darcs"; then
  DARCS_VERSION_STATE=`perl release/determine_release_state.pl $DARCS_VERSION`;
  I_AM_IN_REPO=1
else
  I_AM_IN_REPO=0
  if test -f "release/STATE"; then
    DARCS_VERSION_STATE=`head -n 1 release/STATE`
  else
    DARCS_VERSION_STATE="unknown"
  fi
fi
AC_MSG_RESULT($DARCS_VERSION_STATE)

AC_SUBST(DARCS_VERSION)
AC_SUBST(DARCS_VERSION_STATE)
AC_SUBST(I_AM_IN_REPO)

dnl Get rid of the lousy '-g -O2' defaults

CFLAGS=$CFLAGS

dnl Find gcc

AC_PROG_CC
AC_PROG_CPP

dnl Make sure a decent "install" is installed.

AC_PROG_INSTALL

dnl Find ghc

AC_CHECK_PROG(GHC, ghc, ghc)
if test -z "$GHC"; then
    AC_MSG_ERROR([Cannot find ghc in your path; please set the GHC environment variable!!])
fi
AC_SUBST(GHCFLAGS)

dnl Make sure compiler actually works:

TRY_COMPILE_GHC([main = putStr "Hello world!\n"],,
                AC_MSG_ERROR(Compile failed.))

AC_MSG_CHECKING([where GHC keeps its libraries])
GHC_LIBDIR=$(${GHC} --print-libdir)

if test -z "$GHC_LIBDIR"; then
    AC_MSG_WARN([Couldn't find GHC library path])
else
    AC_MSG_RESULT($GHC_LIBDIR)
fi
AC_SUBST(GHC_LIBDIR)

INIT_WORKAROUND

dnl Figure out how to convert a file descriptor to a Handle

WORKAROUND_openFd

dnl Handle posix signals nicely:

WORKAROUND_POSIXSIGNALS([installHandler, Handler(..), Signal,
                         sigINT, sigHUP, sigABRT, sigALRM, sigTERM, sigPIPE,])

AC_CHECK_HEADERS([siginfo.h])

dnl Look for Text.Regex

GHC_CHECK_MODULE(Text.Regex( mkRegex, matchRegex, Regex ), text, mkRegex undefined)
GHC_CHECK_MODULE(Text.Regex( mkRegex, matchRegex, Regex ), regex-compat, mkRegex undefined)

dnl See if we need a package for QuickCheck

GHC_CHECK_MODULE(Debug.QuickCheck( quickCheck ), QuickCheck, quickCheck True,,
                 AC_MSG_ERROR(Cannot find Debug.QuickCheck; try installing package quickcheck?))

dnl See if we need the util or mtl packages for Control.Monad

GHC_CHECK_MODULE(Control.Monad.Error, util, strMsg "foo" :: String)
GHC_CHECK_MODULE(Control.Monad.Error, mtl, strMsg "foo" :: String,,
                 AC_MSG_ERROR(Cannot find Control.Monad.Error; try installing package mtl?))

dnl See if we need a package for parsec...

GHC_CHECK_MODULE(Text.ParserCombinators.Parsec, parsec, errorPos undefined)

dnl Check if we need package html

GHC_CHECK_MODULE(Text.Html, html, text "foo",,
                 AC_MSG_ERROR(Cannot find Text.Html; try installing package html?))

dnl Deal with systems on which getCurrentDirectory uses '\\' rather than '/':

WORKAROUND_getCurrentDirectory
AC_SUBST(GHC_SEPARATOR)

dnl Deal with systems without createLink

WORKAROUND_createLink

dnl Deal with GHCs without createDirectoryIfMissing

WORKAROUND_createDirectoryIfMissing

dnl Handle systems with a buggy renameFile

WORKAROUND_renameFile

dnl Deal with systems without bracketWithError

WORKAROUND_bracketOnError

dnl Handle systems that don't do POSIX file modes

WORKAROUND_fileModes

WORKAROUND_executable

dnl Make default to have optimizations on...

AC_MSG_CHECKING([whether to optimize])
AC_ARG_ENABLE(optimize,
              AS_HELP_STRING([--disable-optimize],[disable optimization]),
              optimize=$enableval, optimize=yes)
AC_MSG_RESULT($optimize)

if test "$optimize" = yes; then
   GHCFLAGS="$GHCFLAGS -O -funbox-strict-fields"
   if test "$CFLAGS" = ""; then
      CFLAGS="$CFLAGS -O2"
   fi
fi

dnl Handle CPPFLAGS...

GHCFLAGS="$GHCFLAGS $CPPFLAGS"

dnl Make default to not profile...

AC_MSG_CHECKING([whether to profile])
AC_ARG_ENABLE(profile,
              AS_HELP_STRING([--enable-profile],[enable profiling]),
              profile=$enableval,profile=no)
AC_MSG_RESULT($profile)

if test "$profile" = yes; then
   GHCFLAGS="$GHCFLAGS -prof -auto-all"
fi

dnl See if we want to use mmap... for the moment just default to no.

AC_MSG_CHECKING([whether to use mmap])
AC_ARG_ENABLE(mmap, AS_HELP_STRING([--disable-mmap],
              [do not use mmap (use this flag if you get bus errors)]),
              enable_mmap=$enableval,enable_mmap=yes)
AC_MSG_RESULT($enable_mmap)
USE_MMAP="True"
if test "$enable_mmap" = "no"; then
    USE_MMAP="False"
fi
AC_SUBST(USE_MMAP)

TARGETS="darcs doc/darcs.1"
INSTALLWHAT="installbin"
BUILDDOC="no"

dnl Check whether to generate the AUTHORS and ChangeLog files...
if test -d "_darcs"; then
  TARGETS="$TARGETS AUTHORS ChangeLog"
fi

dnl Check whether to use crazy PackedString debugging...

AC_MSG_CHECKING([whether to do PackedString debugging])
AC_ARG_ENABLE(debug-ps,
              [  --enable-debug-ps       enable PackedString debug mode],
               debugps=$enableval, debugps=no)
AC_MSG_RESULT($debugps)


if test "$debugps" = yes; then
   GHCFLAGS="$GHCFLAGS -DDEBUG_PS"
fi

dnl See if we want to use wxhaskell...

AC_MSG_CHECKING([whether to use wxhaskell])
AC_ARG_WITH(wx,
            AS_HELP_STRING([--with-wx],
                           [use wxhaskell to provide a GUI interface]),
           ,with_wx=no)
AC_MSG_RESULT($with_wx)
if test "$with_wx" = "yes"; then
    GHC_CHECK_MODULE(Graphics.UI.WX, wx, undefined,
                     GHCFLAGS="$GHCFLAGS -DHAVEWX -package wx",
                     AC_MSG_WARN([Couldn't find wx package]))
fi

dnl Find latex and friends

AC_MSG_CHECKING([whether to build docs])
AC_ARG_WITH(docs,
	AS_HELP_STRING([--without-docs],
                           [do not try to build docs]),
           ,with_docs=yes)
AC_MSG_RESULT($with_docs)

if test "$with_docs" = "yes"; then
	AC_CHECK_PROG(LATEX, latex, latex)
	if test -z "$LATEX"; then
	AC_MSG_WARN([Cannot find latex in your path!])
	fi
	AC_CHECK_PROG(DVIPS, dvips, dvips)
	if test -z "$DVIPS"; then
	AC_MSG_WARN([Cannot find dvips in your path!])
	fi
	if test ! '(' '(' -z "$LATEX" ')' -o '(' -z "$DVIPS" ')' ')'; then
	TARGETS="$TARGETS doc/manual/darcs.ps"
	INSTALLWHAT="$INSTALLWHAT installdocs"
	BUILDDOC="yes"
	fi
	AC_CHECK_PROG(LATEX2HTML, latex2html, latex2html)
	if test -z "$LATEX2HTML"; then
	AC_MSG_WARN([Cannot find latex2html in your path!])
	PREPROCHTML=""
	AC_CHECK_PROG(HTLATEX, htlatex, htlatex)
	if test -z "$HTLATEX"; then
		AC_MSG_WARN([Cannot find htlatex in your path either!])
		AC_CHECK_PROG(HEVEA, hevea, hevea)
		if test -z "$HEVEA"; then
		AC_MSG_WARN([Cannot find hevea in your path either!])
		MAKEMANUAL="touch doc/manual/index.html; echo Cannot make manual!"
		else
		TARGETS="$TARGETS doc/manual/index.html"
		MAKEMANUAL="$HEVEA -o doc/manual/index.html src/darcs.tex"
		fi
	else
		TARGETS="$TARGETS doc/manual/index.html"
		MAKEMANUAL="cd doc/manual && $HTLATEX ../../src/darcs.tex && ln -sf darcs.html index.html"
	fi
	else
	TARGETS="$TARGETS doc/manual/index.html"
	MAKEMANUAL="$LATEX2HTML -split +1 -dir doc/manual src/darcs.tex"
	dnl the following tells "preproc" to generate "rawhtml" sections for latex2html.
	PREPROCHTML="--html"
	fi
else
	BUILDDOC="no"
fi

AC_SUBST(TARGETS)
AC_SUBST(MAKEMANUAL)
AC_SUBST(INSTALLWHAT)
AC_SUBST(PREPROCHTML)

dnl Look for sendmail...

AC_ARG_WITH(sendmail, [  --with-sendmail=PATHTOSENDMAIL],
[
SENDMAIL=$with_sendmail
HAVE_SENDMAIL="True"
],[
STUPID_PATH=/usr/sbin:/usr/lib
AC_PATH_PROG(SENDMAIL, sendmail, "", $PATH:$STUPID_PATH)
if test -z "$SENDMAIL"; then
    SENDMAIL=""
    HAVE_SENDMAIL="False"
else
    HAVE_SENDMAIL="True"
fi
])
AC_SUBST(SENDMAIL)
AC_SUBST(HAVE_SENDMAIL)

dnl Look for MAPISendMail

AC_CHECK_LIB(mapi32, MAPISendMail, HAVE_MAPI="True", HAVE_MAPI="False")
AC_SUBST(HAVE_MAPI)

if test "$HAVE_SENDMAIL" = "False" -a "$HAVE_MAPI" = "False"; then
    AC_MSG_WARN([Can't find sendmail or mapi so you won't be able to push by email!])
fi

dnl Allow use of color in output to be disabled

AC_ARG_ENABLE(color, AS_HELP_STRING([--disable-color],[do not use ansi color escapes]))

dnl export color flag
USE_COLOR="True"
if test "$enable_color" = "no"; then
    USE_COLOR="False"
fi
AC_SUBST(USE_COLOR)

dnl Find awk

AC_PROG_AWK

dnl Try to link with static versions of libraries.

AC_ARG_WITH(static-libs, [  --with-static-libs      link with static versions of libraries])
if test "x$with_static_libs" = "xyes"; then
    LDFLAGS="-static $LDFLAGS"
fi

dnl Find libcurl and other libraries needed by hscurl.c

AC_ARG_WITH(libcurl,
            AS_HELP_STRING([--without-libcurl],[do not use libcurl]))

CURLLDFLAGS=

if test "$with_libcurl" != "no"; then
 AC_MSG_CHECKING([for libcurl])
 if eval curl-config --version 2>/dev/null >/dev/null; then
   ver=`curl-config --version | sed -e "s/libcurl //g"`
   if test -z "$AWK"; then
       CURLLDFLAGS=`curl-config --libs | sed "s_-arch @<:@^ @:>@+__"`
   else
       CURLLDFLAGS=`curl-config --libs | $AWK '{sub(/-arch @<:@^ @:>@+/,""); print}'`
   fi
   CURLCFLAGS=`curl-config --cflags`
   if test "x$with_static_libs" = "xyes"; then
       CURLCFLAGS="$CURLFLAGS -DCURL_STATICLIB"
   fi
   AC_MSG_RESULT($ver)
 else
   AC_MSG_RESULT(FAILED)
   AC_MSG_WARN([curl-config was not found])
 fi
fi

if test "$CURLLDFLAGS" = ""; then
    HAVE_LIBCURL=False
else
    AC_CHECK_LIB(curl, curl_global_init,
                 [HAVE_LIBCURL=True
                  CFLAGS="$CFLAGS $CURLCFLAGS"
                  LDFLAGS="$LDFLAGS $CURLLDFLAGS"],
                 AC_MSG_ERROR(Cannot actually use libcurl; try specifying --without-libcurl.),
                 $CURLCFLAGS $CURLLDFLAGS)
fi
AC_SUBST(HAVE_LIBCURL)

AC_CHECK_HEADER(windows.h, [SYS=windows], [SYS=other])
AC_SUBST(SYS)

dnl Check for libcurses...

AC_ARG_ENABLE(libcurses, [  --without-curses        do not use libcurses])

HAVE_CURSES=False
if test "$with_libcurses" != "no"; then
  # term.h is documented to require curses.h and actually needs it on
  # Solaris, for instance, though not on GNU/Linux.
  AC_CHECK_HEADER(term.h,
      [AC_SEARCH_LIBS(tgetent, [curses ncurses], [HAVE_CURSES=True])], ,
      [#include <curses.h>
      ])
  AC_CHECK_HEADERS([termio.h])	dnl see External.hs
  if test "$HAVE_CURSES" != "True"; then
    AC_MSG_WARN([Cannot find term.h, disabling color.])
  fi
fi
AC_SUBST(HAVE_CURSES)

dnl look for zlib library and header.

AC_CHECK_HEADER(zlib.h, :,
    AC_MSG_ERROR([Cannot find zlib.h; please set the CPPFLAGS environment variable!]))
AC_CHECK_LIB(z, gzopen, LIBS="$LIBS -lz",
    [
    AC_MSG_ERROR(Cannot find system's zlib library; please set the LDFLAGS environment variable!)
    ])

dnl Check whether Git support was requested

AC_MSG_CHECKING([whether to enable Git support])
AC_ARG_ENABLE(git,
              [  --enable-git            enable Git support],
              git=$enableval,git=no)
AC_MSG_RESULT($git)

if test "$git" = yes; then
    AC_ARG_WITH(git-core, AS_HELP_STRING([--with-git-core=path],
			  [path to Git-core source directory]),[
      GIT_LDFLAGS="-L$withval"
      GIT_CPPFLAGS="-I$withval"
      if test -d "$withval" -a -r "$withval/cache.h" ; then true; else
        AC_MSG_WARN([`$withval' does not look like git-core directory!])
      fi],[
      AC_MSG_CHECKING([if there is a git/ in the current directory])
      if test -d "git" -a -r "git/cache.h" ; then
        GIT_LDFLAGS="-Lgit"
        GIT_CPPFLAGS="-Igit"
        AC_MSG_RESULT([yes])
      else
        AC_MSG_RESULT([no])
      fi
      ])
    AC_ARG_WITH(git-includes, AS_HELP_STRING([--with-git-includes=-Ipath],
                [extra CPP options needed to use Git headers]),
		[GIT_CPPFLAGS="$withval $GIT_CPPFLAGS"])

    for shatype in none fake openssl ; do
       case $shatype in
         none)
           SHA_HEADER_DEFINE=
           try=true
           ;;
	 fake)
	   SHA_HEADER_DEFINE='#define SHA1_HEADER <stdio.h>'
           try=true
           ;;
         openssl)
           try=false
           AC_CHECK_HEADER(openssl/sha.h,
             [SHA_HEADER_DEFINE='#define SHA1_HEADER <openssl/sha.h>'
	      AC_SEARCH_LIBS(SHA1_Init, crypto ssl, [try=true])])
           ;;
       esac
       LIBS_save="$LIBS"
       CPPFLAGS_save="$CPPFLAGS"
       LDFLAGS_save="$LDFLAGS"
       CPPFLAGS="$CPPFLAGS $GIT_CPPFLAGS"
       LIBS="-lgit $LIBS"
       LDFLAGS="$GIT_LDFLAGS $LDFLAGS"
       if $try ; then
	 AC_LINK_IFELSE([AC_LANG_PROGRAM([[
$SHA_HEADER_DEFINE
#include "cache.h"]],
					 [[int j = read_cache();
                                           j = j + write_sha1_file(NULL, 0, NULL, NULL);
					 ]])],,[try=false])
       fi
       CPPFLAGS="$CPPFLAGS_save"
       if $try ; then
         AC_MSG_NOTICE([Using Git SHA1 type: $shatype])
         break
       else
         LDFLAGS="$LDFLAGS_save"
         LIBS="$LIBS_save"
       fi
    done
    
    if $try ; then
      git=yes
    else
      git=no
      AC_MSG_FAILURE([Unable to link against git library.])
    fi
fi

GIT_GHC_FLAGS=
if test "$git" = yes; then
    GIT_SRCS="src/Darcs/Repository/GitRepo.lhs src/Darcs/Git.lhs"
    GIT_C_OBJS="src/gitlib.o"
    GHCFLAGS="$GHCFLAGS -DENABLE_GIT"
    for gitflag in $GIT_CPPFLAGS ; do
      case "$gitflag" in
        -D*)  GIT_GHC_FLAGS="$GIT_GHC_FLAGS '$gitflag'" ;;
        *)    GIT_GHC_FLAGS="$GIT_GHC_FLAGS '-optc$gitflag'" ;;
      esac
    done
else
    GIT_SRCS="src/Darcs/Repository/GitRepo.lhs"
    GIT_C_OBJS=
    GIT_GHC_FLAGS=
fi

AC_SUBST(GIT_SRCS)
AC_SUBST(GIT_C_OBJS)
AC_SUBST(GIT_GHC_FLAGS)
AC_SUBST(SHA_HEADER_DEFINE)

dnl Look for a suitable diff command

AC_CHECK_PROGS(DIFF, [gdiff gnudiff diff])

dnl Look for NullSoft Installer System

AC_PATH_PROGS(MAKENSIS, [makensis.exe])

dnl Check endianness

AC_C_BIGENDIAN([BIGENDIAN="True"],[BIGENDIAN="False"])
AC_SUBST(BIGENDIAN)

dnl Write results

dnl Remove these two tests when autoconf >2.59 can be required.
if test -z "${datarootdir}"; then
   datarootdir=${datarootdir:-'${prefix}/share'}
   AC_SUBST(datarootdir)
fi
if test -z "${docdir}"; then
   docdir=${docdir:-'${datarootdir}/doc/${PACKAGE_TARNAME}'}
   AC_SUBST(docdir)
fi

AC_DEFUN([AC_DATAROOTDIR_CHECKED])
OUTPUT_WORKAROUND
AC_CONFIG_FILES([autoconf.mk src/gitlib.h src/Autoconf.lhs src/ThisVersion.lhs
           tools/cgi/darcs.cgi tools/cgi/README tools/cgi/cgi.conf])
AC_OUTPUT

cat <<[EOF]

The build is configured as follows:

    bindir          = $bindir
    sbindir         = $sbindir
    mandir          = $mandir
    datadir         = $datadir
    sysconfdir      = $sysconfdir
    libexecdir      = $libexecdir

    Build Manual    = $BUILDDOC
    Git support     = $git

If you want to adjust any of these values, edit autoconf.mk and
src/Autoconf.lhs -- or run configure with appropriate settings.

[EOF]

dnl Responsibility shifts to the user after this point.
