#!/bin/bash

PACKAGES=`pwd`
cd ../..
GSDLHOME=`pwd`
cd $PACKAGES

GSDLOS=`uname -s |tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
# check for running bash under cygwin
if test "`echo $GSDLOS | sed 's/cygwin//'`" != "$GSDLOS" ;
then
 GSDLOS=windows
fi
if test "x$crossOS" != "x" ; then
  # Override derived value with value explicitly provided in crossOS
  GSDLOS=$crossOS
fi

prefix=""
bindir=""
HOSTTARGETFLAGS=""

# only some of the packages can take environment variables as options to 
# configure 
# format is VAR=value, e.g "LDFLAGS=-static"
ENVIRONMENT=""

# WVWARE compilation enabled by default, can switch it off with --disable-wvware
USE_WVWARE=true
# GDBM compilation enabled by default, can switch it off with --disable-gdbm
USE_GDBM=true
# JDBM compilation enabled by default, can switch it off with --disable-jdbm
USE_JDBM=true
# SQLite support enabled by default, can switch it off with --disable-sqlite
USE_SQLITE=true
# yaz compilation enabled by default, can switch it off with --disable-yaz
USE_YAZ=true
# z3950 server disabled by default, switch it on with --enable-z3950
USE_Z3950=false
# CORBA support disabled by default, switch it on with --enable-corba
USE_CORBA=false
MICO_DIR=default

# parse any arguments given from toplevel configure
while test $# -ne 0; do
    case "$1" in
	--cache-file=*)
	    cache_filename=`echo $1 | sed s/--cache-file=//`
	    # turn relative path into an absolute path
	    cache_dir=`echo $cache_filename | sed 's@/[^/]*$@@'`
	    cache_dir=`cd $cache_dir 2>/dev/null && pwd`

	    cache_basefile=`echo $cache_filename | sed 's@.*/@@'`
	    cache_file="$cache_dir/$cache_basefile"
	    if test ! -f "$cache_file"; then
		CACHE_FILE=""
	    else
		CACHE_FILE="--cache-file=$cache_file"
	    fi
	    ;;
	--disable-wvware)
	    USE_WVWARE=false
	    ;;
	--disable-gdbm)
	    USE_GDBM=false
	    ;;
	--disable-jdbm)
	    USE_JDBM=false
	    ;;
	--disable-sqlite)
	    USE_SQLITE=false
	    ;;
	--disable-yaz)
	    USE_YAZ=false
	    ;;
	--enable-z3950)
	    USE_Z3950=true
	    ;;
	--enable-corba)
	    USE_CORBA=true
	    ;;
	--with-micodir=*)
	    if test $1 = ""; then
	      $1 = "default"
            fi
	    MICO_DIR=$1
	    ;;       
	--prefix=*)
	    prefix=`echo $1 | sed s/--prefix=//`
	    ;;
	--bindir=*)
	    # where to install binaries to
	    bindir=`echo $1 | sed s/--bindir=//`
	    # turn relative path into an absolute path
	    if test -d "$bindir" ; then
	      bindir=`cd "$bindir" ; pwd `
	      cd "$PACKAGES"
	    elif test -z `echo $bindir | sed '/^\// p;D'` ; then
	      rel_bindir="`echo $bindir | sed s@/.*@@`"
	      cd "$rel_bindir"
	      bindir="`pwd`/`echo $bindir | sed s@^[^/]*/@@`"
	      cd "$PACKAGES"
	    else
	      # bindir doesn't exist, and isn't relative
	      true
	    fi
	    ;;
	--host=* | --target=* | --build=*)
	    HOSTTARGETFLAGS="$HOSTTARGETFLAGS $1"
	    ;;
	*)
	    # ignore all other options for now
	    ;;
    esac
    shift
done

# note! Our GSDL package currently always installs into it's source
# directory, ignoring any --prefix given to configure.
# When this is fixed, uncomment the relevant lines below...

##if test -z "$prefix" ; then
prefix="${GSDLHOME}"
##fi

##if test -z "$bindir" ; then
bindir="${prefix}/bin/$GSDLOS"
##fi

libdir="${prefix}/lib/$GSDLOS"

# This loads the top configure's cache file, with variables already set.
if test -f "$cache_file" ; then
  . $cache_file
fi

# we assume that gzip and tar are on the search path.
# non-GNU versions of tar don't take the -z option.


# wget needs libz when it runs its configure
# this used to be provided (incidentally) by gnome-lib
# however, if the gnome-lib extension is off, this failes
# => configure, compile up and install libz here
# => co-opt the openssl directory for installation of libz
#    as this is where wget is directed to look for additional libraries

# configure the libz converter
echo ""
echo "Configuring libz (AKA zlib)"
echo ""

cd "$PACKAGES/libz"
echo "Supressing LDFLAGS global setting as values"
echo "(rk2 setting this to 'LDFLAGS=-static' is not liked by libz"
store_LDFLAGS="$LDFLAGS"
export LDFLAGS=
echo "****DEBUG: ENVIRONMENT = $ENVIRONMENT"

gzip -dc zlib-1.2.11.tar.gz | tar -xf -
cd zlib-1.2.11 && \
./configure $CACHE_FILE --static --prefix="$PACKAGES/openssl" $HOSTTARGETFLAGS

if test x$? != x0 ;
then
  echo "Configuration of libz failed."
  exit 1
fi

# make
echo Making libz
make
if test x$? != x0 ;
then
  echo "Compilation of libz failed."
  exit 1
fi

echo make install
make install
if test x$? != x0 ;
then
  echo "Installation of libz failed."
  exit 1
fi

echo "Restoring LDFLAGS=$store_LDFLAGS"
export LDFLAGS="$store_LDFLAGS"

# The way common-src compiles up expat during the configure stage itself,
# configure openssl (needs to be done before wget)
# and compile openssl during the configure stage itself.
# Needed by wget for https support

echo ""
echo "Configuring openssl"
echo ""
cd "$PACKAGES/openssl"
openssl_pkgname=openssl-1.0.2l
#openssl_pkgname=openssl-1.1.0f
if test ! -d $openssl_pkgname ;
then
  gzip -dc $openssl_pkgname.tar.gz | tar -xf -
fi
cd $openssl_pkgname

# configure
# see the INSTALL file for OpenSSL to see config options for openssl
# --prefix indicates where the generated lib, include and bin folders will go
# --openssldir will contain the manuals and other non-essentials
# BEWARE: The defaults for --prefix and meaning of --openssldir differ between
# versions of openssl. In the earlier version (1.0.* like 1.0.2l), if
# --prefix is not supplied, then the generated lib, include and bin folders
# will also go into --openssldir.
# In the newer version 1.1.* 1.1.0f, if --prefix is not supplied, it will
# try to install the generated lib, include and bin folders into a system place.
# So better to provide both --openssldir and --prefix, for both openssl versions
# to compile succesfully.
# If you ever want to have the .a libraries that building openssl generates,
# then point the --prefix to the $bindir. We currently don't need to put them
# into $bindir/openssl for wget to use, since wget is built against openssl's
# static libraries and therefore wget doesn't need these when running.

# for 64 bit Macs, need to run ./Configure with darwin64-x86_64-cc, rather than ./config
# To overcome an error in openssl's perl script determining the LLVM version, we also need force the
# compilers to be GNU since Clang comes back with an LLVM version that doesn't work out
stored_CC=$CC
stored_CXX=$CXX
ssl_status=-1
if [[ "x$GSDLOS" == "xdarwin" ]] && [[ `uname -m` == *"64" ]] ; then
    echo Darwin 64, using darwin64-x86_64-cc for OPENSSL_HOST
    export CC="gcc"
    export CXX="g++"
    echo ./Configure --openssldir=$PACKAGES/openssl no-shared darwin64-x86_64-cc
    #CC="gcc" CXX="g++" ./Configure --openssldir=$PACKAGES/openssl no-shared darwin64-x86_64-cc
    ./Configure --openssldir=$PACKAGES/openssl no-shared darwin64-x86_64-cc
    ssl_status=$?
    
elif [[ "x$GS_OPENSSL_HOST" != "x" ]] ; then
    echo "have found environment variable GS_OPENSSL_HOST - using that with Configure, instead of running config which will guess the host"
    echo ./Configure --prefix=$PACKAGES/openssl --openssldir=$PACKAGES/openssl  no-shared $GS_OPENSSL_HOST
    # we found that the following needs bash to run as running it directly here (from within ant)
    # as ./Configure had an error, even though the command worked fine on the command line
    bash ./Configure --prefix=$PACKAGES/openssl --openssldir=$PACKAGES/openssl  no-shared $GS_OPENSSL_HOST
    ssl_status=$?

else
    # this will auto guess the system you are running on
     echo ./config --prefix=$PACKAGES/openssl --openssldir=$PACKAGES/openssl no-shared
     ./config --prefix=$PACKAGES/openssl --openssldir=$PACKAGES/openssl no-shared
    ssl_status=$?
fi

if [ $ssl_status != 0 ] ; then
    echo "ERROR: something went wrong with configuring openssl, returning $ssl_status" 
    exit $ssl_status
fi

# make
echo Making OpenSSL

make
# make 'install_sw' is a target this package has for installing just the software,
# skipping the installation of, for example, the man pages
echo make install_sw
make install_sw
# restore the compile flags
export CC=$stored_CC
export CXX=$stored_CXX

# GS3 needs the now-built openssl to set up https. So we copy (hardlink?) the necessary openssl stuff
# Copying is perhaps OK: <12Mb without the manual or 14.4Mb with manuals.
# to GSDL3SRCHOME/bin/$GSDLOS. Not sure if GSDL3SRCHOME is even set during configure
# if this is a GS3 installation. But we have $GSDLHOME.
cd $PACKAGES
gs3_bin_osdir=../../../bin/$GSDLOS
if [[ -f ../../../gs3-setup.sh ]] && [[ -d $gs3_bin_osdir ]] ; then
    # get rid of any openssl copy from a previous installation
    if [ -d $gs3_bin_osdir/openssl ] ; then
	rm -rf $gs3_bin_osdir/openssl
    fi
    mkdir $gs3_bin_osdir/openssl
    cp -r $PACKAGES/openssl/bin $PACKAGES/openssl/certs $PACKAGES/openssl/include $PACKAGES/openssl/lib $PACKAGES/openssl/misc $PACKAGES/openssl/private $gs3_bin_osdir/openssl/.
fi

# now move the include, lib and bin folders to the correct place

# configure the wvWare Word document converter
echo ""
echo "Configuring wvWare"
echo ""

# datadir flag is for default location of wvHtml.xml config file
if test x$USE_WVWARE = xtrue ; 
then

  # Look to see if gnome-lib extension is present and if so, source its devel.bash file
  if [ -d ../../ext/gnome-lib ] ; then
    pushd ../../ext/gnome-lib
    source ./devel.bash
    popd
  fi

  if [ -d ../../../ext/gnome-lib-minimal ] ; then
    pushd ../../../ext/gnome-lib-minimal
    source ./devel.bash
    popd
  fi

  cd "$PACKAGES/wv"
  if [ "x$GSDLOS" = "xdarwin" ]; then
    WV_LDFLAGS="$LDFLAGS -framework CoreFoundation -framework Carbon"
  else
    WV_LDFLAGS="$LDFLAGS"
  fi
  gzip -dc wv-1.2.4-gs.tar.gz | tar -xf -  
  cd wv-gs && \
  ./configure $CACHE_FILE --prefix=$PACKAGES/wv --bindir="$bindir" --libdir="$libdir" --datadir="$prefix/etc/packages" $HOSTTARGETFLAGS --disable-shared --enable-static LDFLAGS="$WV_LDFLAGS"
else
  echo "wvWare support disabled."
  echo "  add '--enable-wvware' to the configure command to include wvWare support."
  echo ""
fi

if test x$? = x1 ;
then
  echo "Configuration of wvWare failed."
  exit 1
fi

# configure the pdftohtml converter
echo ""
echo "Configuring pdftohtml"
echo ""

cd "$PACKAGES/pdftohtml"
gzip -dc pdftohtml_0_36_gs.tar.gz | tar -xf -
cd pdftohtml_gs && \
./configure $CACHE_FILE --prefix="$prefix" --bindir="$bindir" $HOSTTARGETFLAGS $ENVIRONMENT

if test x$? = x1 ;
then
  echo "Configuration of pdftohtml failed."
  exit 1
fi

# rtftohtml converter
echo ""
echo "Configuring rtftohtml"
echo ""

cd "$PACKAGES/rtftohtml"
gzip -dc rtftohtml-gs.tar.gz | tar -xf -
cd rtftohtml_src && \
./configure $CACHE_FILE --prefix="$prefix" --bindir="$bindir" $HOSTTARGETFLAGS

if test x$? = x1 ;
then
  echo "Configuration of rtftohtml failed."
  exit 1
fi

# On darwin, the wget binary that we build (in $GSDLHOME/bin/$GSDLOS/wget) 
# finds a system libiconv, as you'll notice when you run "otool -L wget"
# That's because we expressly don't compile up libiconv on Macs anymore,
# as the Mac system will have the right libiconv installed.

# configure wget
#wget_pkgname=wget-1.15-gs
wget_pkgname=wget-1.17.1-gs
#wget_pkgname=wget-1.19-gs
echo ""
echo "Configuring wget"
echo ""
cd "$PACKAGES/wget"
gzip -dc $wget_pkgname.tar.gz | tar -xf -
if test x$crossOS = "xandroid" ;
then
  wget_extraargs="gl_cv_header_working_stdint_h=yes ac_cv_func_getopt_long_only=no"
else
  wget_extraargs=
fi

# When compiling wget-1.15-gs without openssl as before:
#./configure $CACHE_FILE --prefix=$PACKAGES/wget --without-ssl --bindir="$bindir" -disable-nls $HOSTTARGETFLAGS $wget_extraargs

# We weren't compiling up wget statically before either and we still aren't
# However, to compile up wget (statically or not) with openssl, as we do now to support retrieving from https urls, see
# https://stackoverflow.com/questions/9817337/compiling-wget-with-static-linking-self-compiled-openssl-library-linking-issu
# Note: contrary to the instructions at the link, if the cppflags and ldflags are set during the
# configure stage, as we now do, then the make command needn't additionally set them as well.
# So just make, make install works thereafter

echo copying "$PACKAGES/wget/wgetrc-gs.in" file to "$bindir/wgetrc"
cp "$PACKAGES/wget/wgetrc-gs.in" "$bindir/wgetrc"

# for wget-1.15-gs. (can also try adding --localstatedir="$bindir/wget" --enable-iri)
##echo CPPFLAGS="-I$PACKAGES/openssl/include $CPPFLAGS" LDFLAGS="-L$PACKAGES/openssl/lib $LDFLAGS" ./configure $CACHE_FILE --prefix=$PACKAGES/wget --with-ssl=openssl --bindir="$bindir" -disable-nls $HOSTTARGETFLAGS $wget_extraarg
##cd "$PACKAGES/wget/$wget_pkgname" && \
##CPPFLAGS="-I$PACKAGES/openssl/include $CPPFLAGS" LDFLAGS="-L$PACKAGES/openssl/lib $LDFLAGS" ./configure $CACHE_FILE --prefix=$PACKAGES/wget --with-ssl=openssl --bindir="$bindir" -disable-nls $HOSTTARGETFLAGS $wget_extraargs

# for wget-1.17.1-gs and wget-1.19-gs (can also try adding --localstatedir="$bindir/wget" --enable-iri)
# The following ran in to a problem on a Linux (centos) machine with lib32 and lib64 libraries.  It tested for
# openssl/lib64 when in fact the folder we produce is 'openssl/lib' causing ./configure to bail 
#echo OPENSSL_CFLAGS="-I$PACKAGES/openssl/include" OPENSSL_LIBS="-L$PACKAGES/openssl/lib -lssl -lcrypto" ./configure $CACHE_FILE --prefix=$PACKAGES/wget --with-ssl=openssl --with-openssl=auto --with-libssl-prefix="$PACKAGES/openssl" --bindir="$bindir" -disable-nls $HOSTTARGETFLAGS $wget_extraargs
#cd "$PACKAGES/wget/$wget_pkgname" && \
#OPENSSL_CFLAGS="-I$PACKAGES/openssl/include" OPENSSL_LIBS="-L$PACKAGES/openssl/lib -lssl -lcrypto" ./configure $CACHE_FILE --prefix=$PACKAGES/wget --with-ssl=openssl --with-openssl=auto --with-libssl-prefix="$PACKAGES/openssl" --bindir="$bindir"  -disable-nls $HOSTTARGETFLAGS $wget_extraargs


echo cd "$PACKAGES/wget/$wget_pkgname"
echo OPENSSL_CFLAGS="-I$PACKAGES/openssl/include" OPENSSL_LIBS="-L$PACKAGES/openssl/lib -lssl -lcrypto -lz -ldl" ./configure $CACHE_FILE --prefix=$PACKAGES/wget --with-ssl=openssl --with-openssl=auto --bindir="$bindir" -disable-nls $HOSTTARGETFLAGS $wget_extraargs
cd "$PACKAGES/wget/$wget_pkgname" && \
OPENSSL_CFLAGS="-I$PACKAGES/openssl/include" OPENSSL_LIBS="-L$PACKAGES/openssl/lib -lssl -lcrypto -lz -ldl" ./configure $CACHE_FILE --prefix=$PACKAGES/wget --with-ssl=openssl --with-openssl=auto --bindir="$bindir"  -disable-nls $HOSTTARGETFLAGS $wget_extraargs



if test x$? = x1 ;
then
  echo "Configuration of wget failed."
  exit 1
fi

xmlparser_as_extra=0
if test $xmlparser_as_extra = 1 ;
then
    # configure XML::Parser perl module
    echo ""
    echo "Configuring XML::Parser"
    echo ""
    cd "$PACKAGES/cpan"

    perl_dir=`echo 'my $vn = sprintf("%vd", $^V); $vn =~ s/\.\d+?$//; print "perl-$vn";' | perl`

    gzip -dc XML-Parser-2.41.tar.gz | tar -xf -
    cd "$PACKAGES/cpan/XML-Parser-2.41" \
	&& perl Makefile.PL \
		PREFIX="$GSDLHOME/perllib/cpan/XML" \
		INSTALLSITELIB="$GSDLHOME/perllib/cpan/$perl_dir" \
		INSTALLSITEARCH="$GSDLHOME/perllib/cpan/$perl_dir" \
		INSTALLMAN1DIR="$GSDLHOME/perllib/cpan/$perl_dir" \
		INSTALLMAN3DIR="$GSDLHOME/perllib/cpan/$perl_dir" \
		SITEPREFIX="$GSDLHOME/perllib/cpan" \
		EXPATINCPATH="$GSDLHOME/common-src/packages/expat/include" \
		EXPATLIBPATH="$GSDLHOME/common-src/packages/expat/lib" \
		INSTALL_BASE=

    if test x$? = x1 ;
    then
	echo "Configuration of XML-Parser failed."
	exit 1
    fi
fi

cpan_extras=0
if test $cpan_extras = 1 ;
then
 # Canary-Stability-2013 was prior to JSON-XS
  for pack in Digest-MD5-2.55 Digest-SHA-5.92 Text-CSV-1.99 JSON-4.10 JSON-XS-4.03 ;
  do 
      cd "$PACKAGES/cpan"
      echo ""
      echo "Unpacking and configuring $PACKAGES/cpan/$pack"
      echo ""
    gzip -dc $pack.tar.gz | tar -xf -
    cd "$PACKAGES/cpan/$pack" \
    && \
      PERL_CANARY_STABILITY_NOPROMPT=1 perl -I "$GSDLHOME/perllib/cpan" Makefile.PL \
       PREFIX="$GSDLHOME/perllib/cpan" \
        INSTALLSITELIB="$GSDLHOME/perllib/cpan/$perl_dir" \
        INSTALLSITEARCH="$GSDLHOME/perllib/cpan/$perl_dir" \
        INSTALLMAN1DIR="$GSDLHOME/perllib/cpan/$perl_dir" \
        INSTALLMAN3DIR="$GSDLHOME/perllib/cpan/$perl_dir" \
        SITEPREFIX="$GSDLHOME/perllib/cpan" \
        INSTALL_BASE=
    if test x$? = x1 ;
    then
      echo "Configuration of $pack failed."
      exit 1
    fi
  done
fi

# configure powerpoint converter
echo ""
echo "Configuring xlhtml (powerpoint & excel converter)"
echo ""
cd "$PACKAGES/xlhtml"
gzip -dc xlhtml-0.4.9.0-gs.tar.gz | tar -xf -
cd xlhtml-0.4.9.0 && \
./configure $CACHE_FILE --prefix="$prefix" --bindir="$bindir" $HOSTTARGETFLAGS

if test x$? = x1 ;
then
  echo "Configuration of xlhtml failed."
  exit 1
fi

# configure IsisGdl program
echo ""
echo "Configuring IsisGdl (CDS/ISIS database reader)"
echo ""
cd "$PACKAGES/isis-gdl" && \
./configure $CACHE_FILE --prefix="$prefix" --bindir="$bindir" $HOSTTARGETFLAGS $ENVIRONMENT

if test x$? = x1 ;
then
  echo "Configuration of IsisGdl failed."
  exit 1
fi

# configure HTMLTidy program
echo ""
echo "Configuring HTMLTidy"
echo ""
cd "$PACKAGES/html-tidy"
CFLAGS_STORE=$CFLAGS
export CFLAGS="$CFLAGS -DNEEDS_UNISTD_H"
gzip -dc tidy.tgz | tar -xf -
cd "$PACKAGES/html-tidy/tidy" && \
./configure $CACHE_FILE --prefix="$prefix" --bindir="$bindir" $HOSTTARGETFLAGS $ENVIRONMENT
export CFLAGS=$CFLAGS_STORE

if test x$? = x1 ;
then
  echo "Configuration of HTMLTidy failed."
  exit 1
fi
