

# -*-shell-script-*-s
# Prerequisites: sed, GNU make, libtool, wget
#
# (and for autogening: GNU m4, GNU autoconf, GNU automake)
#
# libz is optional for the moment

# 1.3  Put RELEASE-NOTES on web site too
# 1.4  Apply both of Ezra's patches of today Wed Mar  2 22:51:36 GMT 2005
#      Update clipper version (the one with shelx .fcf ability) 
# 1.5  Apply Ezra's gtkglarea patch and GSL patch.
#      Update version of FFTW and other updates from MATSUURA Takanori.
# 1.6  Update to mmdb-1.0.8 [# for molrep output]
# 1.7  Fix logic of fftw test
# 1.8  Add the clipper edcalc patch (suggested by Ezra ages ago)
# 1.9  Add Fedora Core 4 support and testing for the need to build mccp4, 
#      mmdb and clipper.
# 1.10 Tidy up nightly code.
# 1.11 Add code testing the need for guile_gui and goosh.
# 1.12 Tidy nightly code again.
# 1.13 Don't escape the "."s in gsub for new gawk (Ward Smith).
# 1.14 20050628 Test for imlib on the installation, not the system (ignore
#               the system).
# 1.15 20050709 Add glib gstrfuncs patch
# 1.16 20050709 Update to guile 1.6.7 and add lt_preloaded_symbols patch
# 1.17 20050721 Added clipper status code to compiling clipper part.
#               Redirect stderr output?
#               fix build_mccp4 problem.
# 1.18 20050722 Fix guile build (wrong http tar file).
#               Added freeglut
# 1.19 20050803 Update version of guile-gtk to 0.41
# 1.20 20050815 Several updates and clean up from MATSUURA Takanori.
# 1.21 20050815 Stop if wget test fails.
# 1.22 20050916 Update build for freeglut to use --disable-warnings and 
#               CFLAGS
# 1.23 20050916 Move "set" so we don't see confusing default coot_version
# 1.24 20051012 Do pre-release tars for a few days.
# 1.25 20051017 Don't make install if Coot's makes fails.  Don't make -k
# 1.26 20051018 Handle clipper nxmap patch.
# 1.27 20051027 [Gif, Paris] Fix tarred directory for nightly pre-release 
#               tars.
# 1.28 20051101 Fix the md5sum for nxmap.h
# 1.29 20051104 Apply most of MATSUURA Takanori's fixes.
#               Use CCP4 libs (mtz, clipper, mmdb).
# 1.30 20051109 Darwin setting of FC for CCP4 libs configure.
# 1.31 20051114 Fix coot tar file problem on building pre-release (or not).
# 1.32 20060205 Add scripting variable debugging (its currently not making 
#               python tar files)   
# 1.33 20060214 Get wget testing tar file from YSBL, not chem.gla
# 1.34 20060219 Correct the install position of libccp4c.la
# 1.35 20060219 create time stamp with current time, not the time of 
#               the previous ccp4 libs file, now the find ctime test works 
#               as I wanted.
# 1.36 20060220 Add a libmmdb.la too.
# 1.37 20060222 Add Bob Nolte's proxy settings
# 1.38 20060224 dylib variable for libmmdb.la and libccp4c.la
# 1.39 20060225 Fix sedding of libmmdb.la and libccp4c.la
# 1.40 20060323 copy over coot.py to share/coot/python (if we built with 
#               python)
# 1.41 20060401 Big changes for ccp4 5.0.2 ccp4c libs.
# 1.42 20060404 Various small build debuggings.
# 1.43 20060405 Fix do_nightlies syntax error and fix up glut_prefix build 
#               problem.
# 1.44 20060405 Fix the tarred directory name when this is not a pre-release
# 1.45 20060406 Check for missing reference structures and monomer lib and 
#               install them if needed.
# 1.46 20060418 use install_top_dir variable to copy over coot.py (not 
#               $coot_prefix!)
# 1.47 20060419 Remove the mmdb binaries
# 1.48 20060420 J. Maclean says no guile. He is right.  So check install for 
#               guile, not system.
# 1.49 20060420 Replace many $AUTOBUILD_INSTALLED with $install_top_dir.
# 1.50 20060421 Replace other $AUTOBUILD_INSTALLED with $install_top_dir for 
#               tar file creation.
# 1.51 20060425 net-http was installing into the wrong place because it had 
#               been set to install_top_dir, but this was not set as a shell 
#               (or configured) variable so it was just blank [James Murray].  
#               Now we export install_top_dir.
# 1.52 20060427 Don't add unecessary tagging of -pre-release to tar_dir at 
#               the end.
# 1.53 20060503 Force GSL to be in $install_top_dir rather than anywhere.
# 1.54 20060519 Update to extract the right coot version from the release and 
#               pre-release directories.
# 1.55 20060621 Shuffle around the test for using pre-release
# 1.56 20060626 Fixes from MATSUURA Takanori. Shuffle around the usage of
#               install_top_dir.
# 1.57 20060704 run imlib-config from the installation, not anywhere.
# 1.58 20060705 Fix wrong directory to build libtiff.
# 1.59 20060706 guile-config should run with an argument, otherise it 
#               returns with exit status 1 (and we test for non-zero). 
# 1.60 20060706 Fix (directory for) mmdb include file test.
# 1.61 20060707 Add to coot configure line the option for guile_gtk
# 1.62 20060708 Fix coot_prerelease_exists typo in setting install_top_dir 
#               (oops).
# 1.63 20060708 Add jpeg dependency for imlib
# 1.64 20060708 Add libungif test to installation, not system (imlib 
#               dependency).
# 1.65 20060710 Add removal of coot_wrap_guile.cc compilation when python 
#               scripting.
# 1.66 20060710 Python on a Sunday. 
# 1.67 20060711 Try to fix up the Makefile for PNG.
# 1.68 20060723 Add in the updates to ltmain.sh, ltconfig and config.guess/sub 
#               for Mactel build.  Add build for readline.
#               Readline version typo fixed.
# 1.69 20060724 ENABLE_PYTHON_COOT variable is tested.  Don't display 
#              a variables if we are using a proxy.
# 1.70 20060728 pass CFLAGS and LDFLAGS to guile's configure
# 1.71 20060730 Add test for 64-bit Linux to update config.xxxs and libtool.
#               Installation readline built now, not system.
# 1.72 20060801 Use mmdb-1.0.8-ysbl-2, which installs includes in the include 
#               dir. This matches clipper cif_data_io.cpp which presumes that 
#               it is there. (And is a clean thing to do anyway).
# 1.73 20060801 Use the new version of libccp4c, with some of Ralf's patches
#               and includes that go into include/ccp4 dir.
# 1.74 20060801 Use CCP4_CXXFLAGS argument to clipper (it does the wrong thing
#               with --with-ccp4)
# 1.75 20060801 Use -pre-2 version of SSMlib, that has -Ixxx/include/mmdb to 
#               find mmdb include files.
# 1.76 20060808 test for libjpeg.$shared_lib_ext not libjpeg.so. LTE bug.
# 1.77 20060818 Force update of libtool and config files for libjpeg.  Extend 
#               the make install proceedure.  Lynn Ten Eyck reported problems 
#               here.
# 1.78 20060823 Add poll fix and getpwuid fix to glib build on Intel Mac.
# 1.79 20060827 Add fix for gtk-canvas from fink for Intel Mac.
# 1.80 20061002 Change freeglut test to test instaltion, not system.
# 1.81 20061012 The path used to find *-config files should be the same one
#               that new executables are added (it was $AUTOBUILD_INSTALLED)
#               and it should be $AUTOBUILD_INSTALLED-pre-release/bin) when
#               we are building a pre-release.
# 1.82 20061012 Change the destination tar file so that there are nightly 
#               and stable directories for the binary tar files on the web
#               server.
# 1.83 20061107 cd to the clipper dir when building clipper.  Pirate and 
#               bucca are not (attempted to be) built then.
# 1.84 20061107 Capture and report error status from make in GSL (intel mac 
#               build fails).
# 1.85 20061107 Use GSL version 1.8, which includes Charles Ballard's fix for
#               fp_regs.h
# 1.86 20061108 Add fink-based args for configure of gtk for Darwin
# 1.87 20061108 Fix ltmain.sh updating for Gtk (oops!).
# 1.88 20061122 Fix coot tar directory now that we have revision numbers in 
#               tar file name.
# 1.89 20061123 Fix/add test for ssmlib build (now depends on mmdb build) and 
#               libccp4c build (now depends on xxx/include/ccp4/cmtzlib.h).
# 1.90 20061128 Allow the user to specify if the dependencies should be checked
#               on the system or only in the autobuild installed directory.
#               Needs more checks to use this.  Currently only glib and gtk
#               tests.
# 1.91 20061211 Don't make install for guile-gtk if the make fails - or the 
#               dependency check for guile-gtk in coot's configure passes 
#               when it should fail (maybe).
# 1.92 20061212 Apply Charles Ballards libtool patch for Macs for imlib and 
#               guile-gtk.
# 1.93 20061212 Fiddle the env vars to compile gtk+ on Mac.
# 1.94 20070104 Non-pre-release build problems, BINARY_DEST_DIR
# 2.01 20070109 imlib tar gz should be downloaded from the correct directory 
#               (sigh).
# 2.02 20070117 Try to compile clipper with -fno-strict-aliasing
# 2.03 20070123 Tell us where the gtkglarea include file was found.
# 2.04 20070124 GCC 3.2 on RH8 machine cannot compile new clipper, so add a
#               patch if needed.
# 2.05 20070216 Put libtiff after libjpeg and give tiff's configure command
#               line args to find jpeg.
# 2.06 20070306 Put in the clipper<->ccp4 new dist patch.
# 2.07 20070319 Remove == comparisons - Lothar Esser.
# 2.08 20070424 --with-jpeg-lib-dir should be a lib dir!
# 2.09 20070501 Fix the setting of coot_version when no pre-release set.
# 2.10 20071002 Post install slim the binaries.  Add helper functions.
# 2.11 20071005 Add some debugging to make_tar.  It doesn't seem to work 
#               currently.
# 2.12 20071005 Fix post_install_slim call.
# 2.13 20071005 Fix slim_dir
# 2.14 20071006 Adjust python scripting settings, so that it should try
#               to compile with python most of the time now.
# 2.15 20071008 Fix extra fi, uncommented typo.
# 2.16 20071010 ENABLE_PYTHON_COOT=no for now.
# 2.17 20071105 Swap out DL Clipper for York clipper [whoosh, bang, kerpow!]
#               enable-cns
# 2.18 20071105 Backpeddle to mmdb 1.08.  Baah.
# 2.19 20071108 Version 1.08-ysbl-3 of mmdb.
# 2.20 20071118 No longer make the full fat tar file.
# 2.21 20071120 Sourcefource no longer distributes libungif, now in 
#               ysbl software/extras
# 2.22 20071121 set the architecture for ubuntu systems.
# 2.23 20071125 Fix typo in recent fixes.
# 2.24 20071126 Fix setting of systype for MacOSX, hopefully.
# 2.25 20071126 Another try to fix setting of systype for MacOSX.
# 2.26 20071130 Try to enable python
# 2.27 20071207 More python tinkering.  Upgrade to 2.5.1
# 2.28 20071207 Add greg. If in York, use it to test before installing.
# 2.29 20071208 Setup CCP4 and use it to test coot before making binaries. 
# 2.30 20071209 Add dewinter's ccp4 setup in setup_ccp4.
# 2.31 20071212 Redirect testing output to $LOGS/$HOST-testing.log
# 2.32 20071213 Copy over the ChangeLog, README and RELEASE-NOTES on good test
# 2.33 20071215 Pythonize only sometimes, default off.
# 2.34 20071215 Tell us some Python info
# 2.35 20071215 Python settings outside the subshell.
# 2.36 20071219 Set up for testing and tars on biop too.
# 3.00 20080108 Gtk+-2 version
# 3.01 20080118 Add GtkGlExt
# 3.02 20080121 Tinker with guile build settings.
# 3.03 20080124 Build GTK2 from scratch: librsvg, cairo, pango, glitz. glib, gtk+-2
# 3.04 20080128 Add a test for the existance of pygtk
# 3.05 20080129 Add pkg-config and pygobject 
# 3.06 20080130 Add test for pycairo
# 3.07 20080130 pycairo needs 1.4.12 - so test for cairo, setting build_gtk=1 on 
#               failure
# 3.08 20080130 Remove static patch (for sgi).  Add test/build for freetype2
# 3.09 20080130 fontconfig added too.
# 3.10 20080131 Change HOSTLOGDIR to include gtk2 to separate it from gtk1 build logs.
# 3.11 20080201 Fix problem in scripting args to coot's configure.
# 3.12 20080207 Add test and build of ATK, needed for gtk+2.10.x
# 3.13 20080208 lib cleaning problems, add debugging.
# 3.14 20080208 Try requiring gtk 2.10
#
# BL says:: I should do build versioning tooo!
# let's start with 1.1
#
# 1.1 08/05/11 switch to new style Refmac library
# 1.2 25/06/11 apply clipper thread patch
# 1.3 31/07/11 add proper goocanvas.
# 1.4 25/02/12 Use libccp4c-5.0.2-ysbl-3.tar.gz, that has libccp4c_la_LIBADD.
# 1.5 26/08/12 Update curl to libcurl_version=7.27.0
# 1.6 27/08/12 Remove old stable installed files before making new stable.
# 1.7 22/09/12 update to mmdb 1.24.2
# 1.8 01/10/12 use mkdir_maybe, make sure glut things are copied in dirs,
#              use make -r flag for coot (speed up)
# 1.9  24/01/13 Move pre-release and release server-dir to Cambridge.
# 1.10 04/02/13 Refmac dictionary 5.39
#               href to get pre release version
# 1.11 28/02/13 New mmdb version - 1.25.0
# 1.12 28/04/13 mmdb version bump 1.25.2
#               update to LMB-MRC download locations
# 1.13 14/05/13 Add COOT_BUILD_INFO_STRING
# 1.14 14/05/13 remove install_top_dir before stable install
# 1.15 06/06/13 For Release 0.7.1, change release vs pre-release logic
#               (MRC server)
# 1.16 18/06/13 More tinkering to get correct version for release from server.
# 1.17 08/07/13 Adjust to build stable logic.
# 1.18 18/08/13 Use ssm-1.3 and update mmdb tar server spec.
# 1.19 04/09/13 Enable veryclean build, i.e. remove build dir, by flag
# 1.20 xxxxx/14 merged with pre 0.8 script
# 1.21 xxxxx/14 various updated binary downloads (NAME?FIXME)
# 1.22 11/07/14 use msys guile binaries
# 1.23 19/10/14 update to mmdb 2, ssm 1.4, bring in line with build-it
#               new place for python install (prefix/pythonxy)
# 1.24 06/01/15 Add WGETO
script_version=1.24

# :: NOTE:: 
# this "strange" construction of variable names: x=${x:=thing} sets the 
# variable x only if it has not previously been defined.
#
# So, the idea is that you write a wrapper for this script (defining typically 
# AUTOBUILD_INSTALLED, AUTOBUILD_BUILD, LOGS and build_coot_prerelease) then
# source this file.  That means that you (probably) don't have to edit your 
# version of build-it every time it changes.


# ENABLE_PYTHON_COOT: if ENABLE_PYTHON_COOT is set to 0 or "no" then
# python coot is not enable (guile coot is enabled).  if
# ENABLE_PYTHON_COOT is set, but not set to 0 or no then python coot
# is enabled.  If ENABLE_PYTHON_COOT is not set, the guile-coot is
# enabled (python coot is not enabled).

# Pythonizing coot makes non-transferable binararies (why?).  Let
# the pythonness be controlled on the command line:
#
ENABLE_PYTHON_COOT=yes

# for Windows we shall have an option to enable Guile and python is default
if [ "$1" = "guile" ] ; then 
   ENABLE_GUILE_COOT=yes
   build_type=-guile
else 
   ENABLE_GUILE_COOT=no
   build_type=
fi

# better do with argv/case or similar
make_clean_coot=
if [ "$1" = "clean" ] ; then 
    make_clean_coot=yes
fi
if [ "$2" = "clean" ] ; then 
    make_clean_coot=yes
fi

# better do with argv/case or similar
make_from_scratch=
if [ "$1" = "veryclean" ] ; then 
    make_from_scratch=yes
fi
if [ "$2" = "veryclean" ] ; then 
    make_from_scratch=yes
fi


# Set the host and the OS.
# Fairly fundamental.
#
OS=`uname`
HOST=`hostname`
HOST=`echo $HOSTNAME | tr '[A-Z]' '[a-z]'`

# Do we need to use a proxy server to get documents from the web? (set
# to 1 if we do)
use_proxy=${use_proxy:=}
# if we do need a proxy then we should give the proxy host and port too:
proxy_host=${proxy_host:=myproxy.com}
proxy_port=${proxy_port:=800}
no_proxy=${no_proxy:=".corp.net.com"}

# This is where the compiled binaries/libraries/data get installed:
# Note that the directory name must NOT end in a /
#
AUTOBUILD_INSTALLED=${AUTOBUILD_INSTALLED:=${HOME}/autobuild/${OS}-${HOST}}
# or perhaps, for the adventurous:
#AUTOBUILD_INSTALLED=$CCP4_MASTER

# This is where the actual build (compilation) master directory is:
# a temporary or scratch directory would be sensible.
# 
# AUTOBUILD_BUILD=${HOME}/autobuild
# I'm putting my build on "scratch space"
AUTOBUILD_BUILD=${AUTOBUILD_BUILD:=$HOME/autobuild}

# This is where the build logs go:
# suggested value:
# LOGS=$AUTOBUILD_BUILD/logs
# but I want to put my log file on the web, so I put them here:
LOGS=${LOGS:=$HOME/public_html/build-logs/${OS}-${HOST}}
PUBLIC_HTML_LOGS=/z/build-logs

# set this to "no" if you don't want to compile the pre-release code.
# build_coot_prerelease=
build_coot_prerelease=${build_coot_prerelease:=1}

# We shall we check dependencies?  
#
# Should we look for gtk etc on the system or only in the installed
# build directory? We want to do the first if we are a person using
# this build script to build coot themselves and we want to do the
# second to build a external-dependency-free coot build (like making
# the binary tars distributed from York).

# check_dependencies_in_install_only=
check_dependencies_in_install_only=1

# get build specials, e.g. change the compiler or the compiler options
# (e.g build for debugging), extra libraries etc setup LD_LIBRARY_DIR
# (or whatever) to include the autobuild library dir so that
# intermediate (configure compile) programs run and the addition to
# the path of GNU make and wget.
# 
# use this to specify config_extras
# 
# options are: GL_prefix, e.g. SunOS has Mesa Graphics - this is
# where to find them:
#              glut_prefix, optionally can use freeglut
#
# Suggested value: comment out this line
specs=${specs:=$HOME/autobuild/build-scripts/${HOST}-specials}

# Make nightly binary tarballs?
# You probably don't want to do this, so recommended is do_nightlies=0
do_nightlies=${do_nightlies:=1}
# if you do want to build them where should they go?
# NIGHTLY_DEST_DIR=$AUTOBUILD_BUILD
NIGHTLY_DEST_DIR=${NIGHTLY_DEST_DIR:=${HOME}/public_html/software/binaries/pre-release}
# if we are not building a nightly/pre-release, i.e. this is a binary 
# for a stable release, they go somewhere else:
#
STABLE_DEST_DIR=${STABLE_DEST_DIR:=${HOME}/public_html/software/binaries/stable}


# When we fail to extract the correct tar file from the web site, what
# shall we build instead?
#
fallback_coot_version=coot-0.8

# For windows shared and enhanced Ligand compilation
#
# set this to "yes", i.e. 1 if you want to compile wth enhanced ligand 
#
build_enhanced_ligand=${build_enhanced_ligand:=0}
build_shared=${build_shared:=0}

# LE needs shared, so set this too then
if [ $build_enhanced_ligand = 1 ]  ; then
    build_shared=1
    build_boost=1
    build_rdkit=1
else
    build_boost=0
    build_rdkit=0
fi

if [ $build_shared = 1 ]  ; then
    shared_static_flag="--enable-shared --disable-static"
else
    shared_static_flag="--disable-shared"
fi

# not shared yet
shared_lib_ext=dll

# ----------------------------------------------------------------
#   End of tinkering with parameters.
# ----------------------------------------------------------------

# First, check that this is bash.
# 
if [ "$BASH" = "" ] ; then 
   echo this shell is not bash\!
   echo this script must be run with bash\!
   exit
fi


# now the functions:

function mkdir_maybe {

  dir=$1
  if [ ! -e "$dir" ] ; then
     mkdir $dir
  fi

}

# Give args: prefix-dir and (based on is-static-flag) either
# "clear-static" or "clear-dynamic"
#
function post_install_slim {

    echo we are slimming directory $1
    fat_dir="$1"
    cleaned_dir="$2"
    clear_type="$3"
    echo fat_dir is $fat_dir
    echo clear_type is $clear_type
    echo cleaned_dir is $cleaned_dir

    mkdir_maybe $cleaned_dir
    mkdir_maybe $cleaned_dir/bin
    mkdir_maybe $cleaned_dir/lib

    lib_sos=`cd $fat_dir && ls -1 lib/lib*.so*`
    lib_as=`cd $fat_dir && ls -1 lib/lib*.a`

    if [ "$clear_type" = "clear-dynamic" ] ; then
       keep_lib_archs="$lib_as"
    fi

    if [ "$clear_type" = "clear-static" ] ; then
       keep_lib_archs="$lib_sos"
    fi

    for file in etc html info man share bin/coot bin/coot-real \
        bin/findwaters bin/findwaters-real bin/findligand bin/findligand-real \
	bin/guile lib/$python_version $keep_lib_archs ;
    do
       dn=`dirname $file`
       if [ -e $fat_dir/$file ] ; then
          echo rsync -axr $fat_dir/$file $cleaned_dir/$dn
          rsync -axr $fat_dir/$file $cleaned_dir/$dn
       else
          echo $fat_dir/$file does not exist
       fi
    done
    echo done rsyncing.
}


function make_tar {

    echo in make_tar args: $1 $2
    echo in make_tar: in dir: $PWD

    tar_dir=$1
    tar_file_name=$2

    cd $install_top_dir/..
    if [ -e $tar_dir ] ; then
       echo taring nightly... from $tar_dir to $tar_file_name
       tar czf $tar_file_name $tar_dir
       status=$?
       if [ "$status" != 0 ] ; then 
	  echo ERROR:: tar czf $tar_file_name $tar_dir failed.
          echo ERROR:: while in directory $(pwd)
	  echo ERROR:: tar failed > $tar_file_name.md5sum
	  rm $tar_file_name
       else 
	  md5sum $tar_file_name > $tar_file_name.md5sum
	  /bin/ls -l $tar_file_name >> $tar_file_name.md5sum
	  echo done tar successfully.
       fi
    else
       echo ERROR:: tar target directory $tar_dir does not exist.
    fi
}

function setup_ccp4 {

   # we have access to $OS and $arch.

   if test "$OS" = Linux ; then
      setup_file=/y/programs/xtal/ccp4-6.0/ccp4-6.0/include/ccp4.setup-sh 
      if test -e $setup_file ; then
         . $setup_file
      fi
      setup_file=/lmb/dorset/linux_software/ccp4-6.0/include/ccp4.setup-bash
      if test -e $setup_file ; then
         . $setup_file
      fi
   fi
   if test "$OS" = Darwin ; then
      . /usr/local/ccp4-6.0.2/bin/ccp4.setup-sh
   fi
}


# exit 
function my_exit {

   exit_arg=$1
   shift
   extra_args=$*

   # remove evtl. existing coot-version files
   # and installer variable file
   rm -f $install_top_dir/coot-version
   # even if failed 
   # we write a number of variables to a file which we import in the
   # masta script so that we preserve these
   # first remove an the old file
   var_file=${HOME}/wincoot-installer-variables
   echo deleting $var_file
   rm -f $var_file
   echo LOGS=${LOGS}                          > $var_file
   echo NIGHTLY_DEST_DIR=${NIGHTLY_DEST_DIR} >> $var_file
   echo wincoot_version=$wincoot_version     >> $var_file
   echo build_coot_prerelease=$build_coot_prerelease   >> $var_file
   echo coot_build_status=$coot_build_status >> $var_file
   echo coot_test_status=$coot_test_status     >> $var_file
   echo binary_type_latest=$binary_type_latest >> $var_file
   echo HOSTLOG_STUB=$compilers_dir${build_type} >> $var_file

   echo fail-build $extra_args > $LOGS/gtk2${build_type}-test-status
   if [ -e $LOGS/gtk2${build_type}-build-status ] ; then
      rm $LOGS/gtk2${build_type}-build-status
   fi
   exit $exit_arg
}


# Return 0 on success, 1 on failure (or not tested)
#
#
# This can only be run when the coot tar file and greg tests have been
# untared (in this particular build) 
# 
# we should be in the directory where coot was untarred for building 
# when this function was called.
#
function test_coot_guile { 

echo testing with greg
echo testing with greg >&2
echo currently we are here:
pwd
date
if [ "$1" != "" ] ; then
   coot_binary=$1
else
   coot_binary=$install_top_dir/libexec/coot-bin
fi

if test "$run_tests" = true ; then
   # let's test our new coot
   
   # the greg tests are where the coot source code was untarred.
   # 
   if [ ! -d greg-tests ] ; then 
      echo greg-tests dir missing in this directory:
      pwd
      return 1
   fi

   setup_ccp4

   cat <<EOF > command-line-greg.scm
   (use-modules (ice-9 greg))
         (set! greg-tools (list "greg-tests"))
         (set! greg-debug #t)
         (set! greg-verbose 5)
         (let ((r (greg-test-run)))
            (if r
	        (coot-real-exit 0)
	        (coot-real-exit 1)))
EOF

   echo $install_top_dir/bin/coot --no-graphics --script command-line-greg.scm
        $install_top_dir/bin/coot --no-graphics --script command-line-greg.scm

   status=$?
   if [ $status = 0 ] ; then
      echo test_coot: coot test passed
      return 0
   else 
      echo test_coot: coot test failed
      return 1
   fi
else 
   echo run_tests is not true, not testing.
   return 1
fi

}

# Return 0 on success, 1 on failure (or not tested)
#
# we should be in the directory where coot was untarred for building 
# when this function was called.
#
function test_coot_python { 

echo testing with python unittest
echo currently we are here:
pwd
date
if [ "$1" != "" ] ; then
   coot_binary=$1
else
   coot_binary=$install_top_dir/libexec/coot-bin
fi

if test "$run_tests" = true ; then
   # let's test our new coot
   # first clean up coot-backup otherwise we'll fill up the disk
   echo removing old backup-files in coot-backup
   rm coot-backup/*
   # for python build we need to set COOT_PYTHON_DIR and COOT_HOME
   COOT_PYTHON_DIR=$install_top_dir/python27/lib/site-packages/coot
   COOT_HOME=$HOME
   # add lib to path for rdkit and boost
   PATH=$install_top_dir/lib:$PATH
   PYTHONPATH=$COOT_PYTHON_DIR
   PYTHONHOME=$install_top_dir/python27
   export PYTHONPATH
   export PYTHONHOME
   export COOT_PYTHON_DIR
   export COOT_HOME
   
   echo $install_top_dir/bin/coot --no-graphics --script python-tests/coot_unittest.py
        $install_top_dir/bin/coot --no-graphics --script python-tests/coot_unittest.py

   status=$?
   if [ $status = 0 ] ; then
      echo test_coot_python: coot test passed
      return 0
   else 
      echo test_coot_python: coot test failed
      return 1
   fi
else 
   echo run_tests is not true, not testing in python
   return 1
fi

}


function fixup_libcurl { 

    sed s,-L/usr/lib,, curl-config > curl-config.tmp
    mv curl-config.tmp curl-config
    sed s,-L/usr/lib,, lib/libcurl.la > lib/libcurl.la.tmp
    mv lib/libcurl.la.tmp lib/libcurl.la
}



# now on to some code!



if [ "$use_proxy" = 1 ] ; then
# establish proxy settings
  printf "Proxy user: "
  read proxy_user
  printf "Proxy password: "
  read -s proxy_pass
  printf "\n"
  http_proxy="http://${proxy_user}:${proxy_pass}@${proxy_host}:${proxy_port}/"
  https_proxy="http://${proxy_user}:${proxy_pass}@${proxy_host}:${proxy_port}/"
  ftp_proxy="http://${proxy_user}:${proxy_pass}@${proxy_host}:${proxy_port}/"
  ssl_proxy="http://${proxy_user}:${proxy_pass}@${proxy_host}:${proxy_port}/"
  export http_proxy https_proxy ftp_proxy ssl_proxy no_proxy
fi


# use the right (GNU) tar and provide the path to wget (needed
# for downloads) and to GNU make - (which is necesary for python
# at least).
#
# So that python and the *-configs are found when it is installed:
# A bit of a kludge because we do testing for pre-release later.  
# It's a logical mess.
#
#we shall add the PATH for python here too:
# BL says: not sure if we really want the pre install PATH to be set here too
#if test "$build_coot_prerelease" = 1 ; then
#   PATH=${AUTOBUILD_INSTALLED}-pre-release-gtk2${build_type}/bin:${AUTOBUILD_INSTALLED}-pre-release-gtk2${build_type}/python2.5:$PATH
#else 
#   PATH=$AUTOBUILD_INSTALLED-gtk2$build_type/bin:$AUTOBUILD_INSTALLED-gtk2$build_type/python2.5:$PATH
#fi 
#PATH=$PATH:/usr/local/bin:/usr/sbin:/usr/bsd:/sbin:/usr/bin:/bin:
#PATH=$PATH:/etc:/usr/etc
#
#export PATH
#echo PATH is now: $PATH
echo AUTOBUILD_BUILD is $AUTOBUILD_BUILD

# This is where the sources downloaded from network go:
AUTOBUILD_SOURCES=${AUTOBUILD_BUILD}/sources
echo AUTOBUILD_SOURCES is $AUTOBUILD_SOURCES
if (! test -d ${AUTOBUILD_SOURCES}) ; then
   mkdir -p ${AUTOBUILD_SOURCES}
fi


# now make the build logs directory
mkdir -p $LOGS

systype=unknown
update_libtool=0

# malloc.h business, Darwin does not have malloc.h
# used in the gtk_canvas build
have_malloc=1
if test "$OS" = "Darwin" ; then
   have_malloc=0
   fix_ulong=1
   update_libtool=1
   update_config_guess_sub=1
   shared_static_flag="--disable-static"
   shared_lib_ext=dylib
   need_readline_patch=1
   # uname -a gives processor type in last field on Darwin
   processor=$(uname -a | awk '{print $(NF)}')
   need_gtk_imlib_libtool_fix=1
   if test "$processor" = "i386" ; then
      need_glib_getpwuid_fix=1
      need_glib_poll_fix=1
      need_gtk_canvas_patch=1
   fi
   osversion=$(sw_vers -productVersion)
   systype=MacOSX-${osversion}-${processor}
fi

# redirect the output.
#
# exec 2>&1 > $LOGS/$HOST.log
# Try not to redirect standard out so that it goes to
# the sub-shell log?  (testing)
echo INFO:: redirecting std output to $LOGS/gtk2${build_type}-build.log
exec > $LOGS/gtk2${build_type}-build.log
echo This is script version $script_version for Gtk2 

# local tinkering because our sgi runs out of room on /tmp on compiling
if [ $HOST = batman ] ; then
   TMPDIR=$HOME/tmp
   export TMPDIR
fi

date
#
if [ -n "$specs" ] ; then
   if [ -e "$specs" ] ; then
	echo running these extras:
	echo . --------------------------------
	cat "$specs"
	. "$specs"
	echo . --------------------------------
   fi
fi

#initially unset:
architecture=
if test $OS = Linux ; then
  architecture=$(uname -i)
  # uname -i and uname -p (strangely) return unknown on my ubuntu
  if test $architecture = unknown ; then
     architecture=$(uname -m)
  fi
fi
# now architecture is something like i386 or x86_64

# now test for 64 bit Linux:
if test "$OS" = "Linux" ; then
   processor=$(uname -a | awk '{print $NF}')
   # on my Redhat i386, uname returns: 
   # Linux kalypso 2.6.12-1.1398_FC4 #1 Fri Jul 15 00:52:32 EDT 2005 i686 athlon i386 GNU/Linux
   # 64 bit Ubuntu:
   # Linux kalypso 2.6.22-14-generic #1 SMP Sun Oct 14 21:45:15 GMT 2007 x86_64 GNU/Linux
   # from that I presume we need $(NF-2) to get the arch (not NF-1).  Eh?
   # arch=`uname -a | awk '{print $(NF-1)}'`
   arch=$(uname -a | awk '{print $(NF-1)}')
   echo currently architecture is $architecture
   if test "$architecture" = x86_64 -o "$architecture" = ia64 ; then
      update_libtool=1
      update_config_guess_sub=1
   else 
       echo this is not a 64 bit machine
   fi 
fi

if test $OS = Linux ; then 

   if [ -e /bin/rpm ] ; then 
      if rpm -a ; then
         for i in fedora-release redhat-release redhat-release-workstation centos-release sl-release openSUSE-release ; do
           dist=`rpm -q --qf '%{name}' ${i}`
           echo  dist is $dist
           dist=`rpm -q --qf '%{name}' ${i}`
           if test $? = 0 ; then
              dist_name=$(echo ${dist} | sed -e 's/\-release//g' -e 's/\-workstation//g')
              dist_ver=$(rpm -q --qf '%{version}' ${i})
              break
           else
              dist_name='unknown'
           fi
         done
      else
         dist_name='unknown'
      fi
   fi

  case ${dist_name} in

    redhat* )
    case ${dist_ver} in
      [0-9] | [0-9].[0-9]* )
        systype=${architecture}-redhat-${dist_ver}
      ;;
      * )
        systype=${architecture}-rhel-$(echo ${dist_ver} | sed s/[A-Za-z]//g)
        if [ $arch = x86_64 ] ; then 
	   if [ $dist_ver = 4WS ] ; then
	      echo RedHat 4 Linux x86_64 detected. need to update libtool
              update_libtool=1
              # stupid la file of libcur puts /usr/lib in the link path (early).  This causes link 
              # problems on 64 bit RHEL4.  So lets fix curl-config and libcurl.la
              post_process_libcurl=1
	   fi
        fi
      ;;
    esac
    ;;

    fedora | centos | openSUSE )
      systype=${architecture}-${dist_name}-${dist_ver}
    ;;


    sl ) 
      systype=${architecture}-scientific-linux-${dist_ver}
      ;; 


    * )
      if test -r /etc/issue; then
        dist_name=$(awk 'NR==1{print tolower($1)}' /etc/issue)
        if [ "$dist_name" = "debian" ] ; then
           dist_ver=$(awk  'NR==1{x=tolower($2); y=tolower($3); gsub("/","-",x); gsub("/","-",y); print x "-" y}' /etc/issue)
        else
           dist_ver=$(awk  'NR==1{x=tolower($2); gsub("/","-",x); print x}' /etc/issue)
        fi
        systype=${architecture}-${dist_name}-${dist_ver}
      else
        systype=${architecture}-unknown-Linux
      fi
    ;;
  esac
fi


if test $OS = IRIX64 ; then
   osversion=`uname -r`
   systype=${osversion}-sgi
fi

if test $OS = IRIX ; then
   osversion=`uname -r`
   systype=${osversion}-sgi
fi

if test $OS = OSF1 ; then
   osversion=`uname -r | sed s/V//g`
   systype=${osversion}-OSF1
fi

# maybe all can be case
case "$OS" in
   MINGW*) 
     systype=`uname -m`
     architecture=`uname -m`
   ;;
esac

echo systype: $systype

echo update_libtool: $update_libtool
echo update_config_guess_sub: $update_config_guess_sub


# give us some diagnostic shell information:
# (what extra things did $specs give us?)
#
if [ "$use_proxy" = 1 ] ; then
    echo no diagnostic variables, we are using a proxy.
else    
    set
fi

# Do we link with sqlite (for the ligands database)?
# We allow the calling script to set use_sqlite=yes
use_sqlite=${use_sqlite:=no}

if [ "$use_sqlite" = "yes" ] ; then
    sqlite_config_args=--with-sqlite3
else
    sqlite_config_args=
fi

# We want to add some compiler info in the directory name.
# If CC is set, use that,
# If not, try gcc, 
# if not, try cc
#
# Similarly for the c++ compiler info
# If CXX is set, use that
# if not, try g++
# if not, try c++

if [ -n "$CC" ] ; then

        # CC was set
        gcctest=`$CC --version | awk 'NR==1 {print $2}'`
        if [ "$gcctest" != "(GCC)" ] ; then
           # but not gcc 
           v=$CC-`$CC -v`
              if [ $? -ne 0 ] ; then
                 v="missing_version"
              fi
        else
              # gcc
              v=$CC-`$CC --version | awk 'NR==1 {print $3}'`
        fi

else
	# CC not set
	v=gcc-`gcc -dumpversion | head -1`
        if [ $? -ne 0 ] ; then
		# not gcc
	        # try cc
		v=cc-`cc -v`
		if [ $? -ne 0 ] ; then
		   v="missing_version"
		fi
	fi
fi


if [ -n "$CXX" ] ; then

	# CXX was set
	gxxtest=$($CXX --version | awk 'NR==1 {print $2}')
        # typically gxxtest is set to "(GCC)", but not on Ubuntu, where the line is:
	# g++ (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3
        # Scientific Linux:
        # g++ (GCC) 4.4.6 20120305 (Red Hat 4.4.6-4)
        # RHEL 6:
        # g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3)
        echo gxxtest: $gxxtest
	if [ "$gxxtest" != "(GCC)" ] ; then

             # but not g++ (?).  Maybe it was Ubuntu...

             case "$gxxtest" in
                *[Uu]buntu*) 
                   w=$($CXX --version | head -1 | awk '{print $3}' | tr -d ')')
                   ;;
	   
                *) 
                   w=$CXX-$($CXX -v | head -1 | sed 's/ / /g')
   	           if [ $? -ne 0 ] ; then
	    	      w="missing_cxx_version"
	           fi
                   ;; 
             esac
	else 
           # g++
           w=$CXX-$($CXX --version | awk 'NR==1 {print $3}')
	fi
else
	# CXX not set
	w=g++-`g++ -dumpversion | head -1`
        if [ $? -ne 0 ] ; then
		# not g++
	        # try c++
		w=c++-`c++ -v`
		if [ $? -ne 0 ] ; then
		   # try CC
		   w=CC-`CC -v`
		   if [ $? -ne 0 ] ; then
		      w="missing_c++_version"
		   fi
		fi
	fi
        # note that g++ 3.2 cannot compile clipper's test_contrib.cpp.
        # So, if we have g++ 3.2 or less, then we need to get and apply 
        # test_contrib.cpp.patch
        # add a space before argument setting
	awk -v version=$w 'BEGIN{ exit (version+0 >= 3.3)}'
        wvers=$?
        if [ $wvers = 0 ] ; then
	   need_clipper_contrib_patch=true
        fi
fi

# do we actually have g++ (or c++?)
if ! g++ --version ; then
   if ! c++ --version ; then
      echo no c++/g++ compiler.  Exit now
      my_exit 2
   fi
fi




# so now we have v and w set to something.  We 
# need to sanitize that something.  
v_fid=`echo $v | sed 's/ /_/g'`
w_fid=`echo $w | sed 's/ /_/g'`

compilers_dir=gtk2-${v_fid}_and_${w_fid}
HOSTLOGDIR=$LOGS/$compilers_dir${build_type}
if [ ! -e $HOSTLOGDIR ] ; then 
  mkdir -p $HOSTLOGDIR
  if [ $? -ne 0 ] ; then
    #
    echo DISASTER: could not make directory $HOSTLOGDIR
    echo exiting.
    my_exit 2
  fi
fi


echo need_guile_unused_values_patch is $need_guile_unused_values_patch



# need to add test that make is GNU make, and set number of processor if we have 
# enough memory and cpus...
#
echo "Testing version of make"
MAKE=make
if make --version ; then
   # let's try to set some args
   if [ -e /proc/meminfo ] ; then
      memory_kb=$(awk '/MemTotal:/ {print $2} ' /proc/meminfo)
      if [ "$memory_kb" -gt 2000512 ] ; then
         if [ -e /proc/cpuinfo ] ; then
            if np=$(grep processor /proc/cpuinfo | wc -l) ; then
               # limit to 8 processors
               if [ "$np" -gt 8 ] ; then
                  np=8
               fi
               echo using $np processors in compilation
               MAKE="make -j$np"
               echo MAKE set to $MAKE
            fi
         fi
      fi
   fi
   if [ $OS = Darwin ] ; then 
      np=$(system_profiler SPHardwareDataType | awk '/Total Number/ { print $NF }')
      MAKE="make -j$np"
   fi
else 
   # definately not GNU make
   # Try gmake then....
   gmake --version
   if [ $? -ne 0 ] ; then
      nomake=1
   else
      MAKE=gmake
      nomake=0
   fi
   if [ $nomake -eq 1 ] ; then
      echo Ooops.  Your make '(' `which make` ')' is not GNU make and gmake not found.
      echo Exiting now.
      my_exit 2
   fi
fi

echo testing for patch 
patch --version > /dev/null
if [ $? -ne 0 ] ; then
   echo no patch - exit now
   my_exit 2
fi

echo testing awk type \(prefer GNU awk\)
if awk --version ; then
   echo good, you have an awk from GNU.
else
   echo WARNING:: awk is not a GNU awk, trouble ahead possibly.
fi


# create $AUTOBUILD_BUILD directory

if [ ! -d "$AUTOBUILD_BUILD" ] ; then
   mkdir "$AUTOBUILD_BUILD"
   if [ $? -ne 0 ] ; then

        prev_dir=$(dirname $AUTOBUILD_BUILD)
        echo $prev_dir
        if [ ! -d "$prev_dir" ] ; then
           mkdir $prev_dir
           mkdir "$AUTOBUILD_BUILD"
        fi
   fi

   if [ ! -d "$AUTOBUILD_BUILD" ] ; then
      # echo mkdir of the AUTOBUILD_BUILD \(i.e. "$AUTOBUILD_BUILD"\) failed.
      my_exit 2
   fi

fi
   

cd $AUTOBUILD_BUILD
if [ $? -ne 0 ] ; then
	echo $AUTOBUILD_BUILD failed for some reason. Now in `pwd`
fi
# for ccp4 (20051104) compatibility, we can't use colons in the date string
date=$(date -u +'%Y-%m-%d__T%H_%M_%S')
echo Date: $date

# now in $AUTOBUILD_BUILD
# we dont want to have the 'stupid' date and time in there...
# I dont like it
mkdir_maybe ${HOST}${build_type}
if [ $? -ne 0 ] ; then
	echo mkdir  ${HOST}${build_type} failed for some reason. Now in `pwd`
fi
cd ${HOST}${build_type}
if [ $? -ne 0 ] ; then
	echo cd ${HOST}${build_type} failed for some reason. Now in `pwd`
fi
build_dir=`pwd`

echo checking wget
echo which wget
which wget
# use -P for timestamping
# Note that now wget depends on libhogweed and that depends on libgmp
# but we are compiling an old version of gmp (not sure that we need
# an old version) and libhogweed refers to a (now) non-existant
# functions and the dynamic loading fails.
# This setting of the alias fails.  It works on the command line.
# WGET="LD_LIBRARY_PATH=/usr/lib wget -N -P ${AUTOBUILD_SOURCES}"
# WGETO="LD_LIBRARY_PATH=/usr/lib wget   -P ${AUTOBUILD_SOURCES}"
WGET="C:\msys64\usr/\bin\wget.exe  -nv -N -P ${AUTOBUILD_SOURCES}"
WGETO="C:\msys64\usr/\bin\wget.exe -nv    -P ${AUTOBUILD_SOURCES}"
WGETS="C:\msys64\usr/\bin\wget.exe --no-check-certificate -N -P ${AUTOBUILD_SOURCES}"

# latest version (without .tar.gz extension)
coot_version=$fallback_coot_version

pre_release_server_dir=http://www.ysbl.york.ac.uk/~emsley/software/pre-release/
pre_release_server_dir=http://lmb.bioch.ox.ac.uk/coot/software/source/pre-releases/
pre_release_server_dir=http://www2.mrc-lmb.cam.ac.uk/groups/murshudov/coot/source/pre-releases/
pre_release_server_dir=http://www2.mrc-lmb.cam.ac.uk/personal/pemsley/coot/source/pre-releases
pre_release_server_dir=https://www2.mrc-lmb.cam.ac.uk/personal/pemsley/coot/source/pre-releases/0.9-pre
pre_release_server_dir=https://www2.mrc-lmb.cam.ac.uk/personal/pemsley/coot/source/pre-releases
#
release_server_dir=http://www.ysbl.york.ac.uk/~emsley/software
release_server_dir=http://lmb.bioch.ox.ac.uk/coot/software/source/releases
release_server_dir=http://www2.mrc-lmb.cam.ac.uk/groups/murshudov/coot/source/releases/
release_server_dir=http://www2.mrc-lmb.cam.ac.uk/personal/pemsley/coot/source/releases
#
extras_place=http://www2.mrc-lmb.cam.ac.uk/personal/pemsley/coot/dependencies
win_extras_place=http://bernhardcl.github.io/coot/software/extras


${WGETO} -O ${AUTOBUILD_SOURCES}/index.html -o ${AUTOBUILD_SOURCES}/wget-e.s.p.log $release_server_dir/
${WGETO} -O ${AUTOBUILD_SOURCES}/index-pre-release.html -o ${AUTOBUILD_SOURCES}/wget-e.s.p.log $pre_release_server_dir/
pre_release_files_html="none"
if [ $build_coot_prerelease = 1 ]  ; then 
   pre_release_files_html=${AUTOBUILD_SOURCES}/index-pre-release.html
fi
if [ $build_coot_prerelease = yes ]  ; then 
   pre_release_files_html=${AUTOBUILD_SOURCES}/index-pre-release.html
fi

echo doing the awk on the html $pre_release_files_html
awk ' /a href=.*.tar.gz/ {split($2, arr, "\""); file=arr[2]; gsub(".tar.gz", "", file); print file}' $pre_release_files_html

coot_version_tmp=$(awk  ' /a href=.*.tar.gz/ {split($2, arr, "\""); file=arr[2]; gsub(".tar.gz", "", file); print file}' \
$pre_release_files_html | tail -1)

echo pre_release_files_html $pre_release_files_html
echo coot_version_tmp : $coot_version_tmp :

if [ -z "$coot_version_tmp" ] ; then
    echo clever coot_version extraction failed, using default.
else 
    coot_version=$coot_version_tmp
    echo clever coot_version succeeded, setting coot_version to $coot_version from extraction
fi


# override the switch which turns off the building of the pre-release here:
# build_coot_prerelease=1

# Let's initially set coot_prerelease_exists to not-exist, then we 
# try to download it from the Coot web site, and if it exists we set 
# coot_prerelease_exists to 1.  If it doesn't exist, we don't do that 
# of course and we also don't make the install_top_dir to be the pre-release
# directory later on.
coot_prerelease_exists=

# coot_version_pre no longer has .tar.gz extension

echo =========================== build_coot_prerelease currently is $build_coot_prerelease ========================

if test "$build_coot_prerelease" = 1 ; then 

   echo debug:: ${WGETO} -O ${AUTOBUILD_SOURCES}/index.html -o ${AUTOBUILD_SOURCES}/wget-e.s.p.log $pre_release_server_dir/
   ${WGETO} -O ${AUTOBUILD_SOURCES}/index.html -o ${AUTOBUILD_SOURCES}/wget-e.s.p.log $pre_release_server_dir/
   coot_version_pre=$(awk  ' /a href=.*.tar.gz/ {f=$2; split(f, arr, "\""); file=arr[2]; gsub(".tar.gz", "", file); print file}' \
       ${AUTOBUILD_SOURCES}/index.html | tail -1)

   echo INFO:: building pre-release and coot_version_pre is $coot_version_pre
   if [ -z "$coot_version_pre" ] ; then
      # this path when there are no pre-releases to be built, i.e. build the latest release.
      echo trying to build pre-release coot, but failed to find pre-release version
      echo make a stable release then
      build_coot_prerelease=
      BINARY_TAR_DEST_DIR=$STABLE_DEST_DIR
      mkdir -p ${BINARY_TAR_DEST_DIR}
      mkdir -p ${BINARY_TAR_DEST_DIR}/holding  # not needed?!

      ${WGETO} -O ${AUTOBUILD_SOURCES}/index.html -o ${AUTOBUILD_SOURCES}/wget-e.s.p.log $release_server_dir
      echo examining release server files ${AUTOBUILD_SOURCES}/index.html
      coot_version=$(awk  ' /compressed.*a href=/ {f=$6; split($6, arr, "\""); file=arr[2]; gsub(".tar.gz", "", file); files[file]=1; } END { for (file in files) { if (file>final) { final=file } } ; print final } ' \
        ${AUTOBUILD_SOURCES}/index.html | tail -1)
      echo coot_version $coot_version


   else
      build_coot_prerelease=1  # belt and braces
      coot_prerelease_exists=1
      # tinker with coot_prefix, it is generic_prefix with pre-release added to prefix dir
      coot_prefix="--prefix=${AUTOBUILD_INSTALLED}-pre-release-gtk2${build_type} ${config_extras:-}"
      coot_source_tar_file=${pre_release_server_dir}$coot_version_pre.tar.gz
      echo DEBUG:: set coot_source_tar_file to $coot_source_tar_file
      coot_version=`echo $coot_version_pre | sed s/\.tar.gz//`
      BINARY_TAR_DEST_DIR=$NIGHTLY_DEST_DIR
      mkdir -p ${NIGHTLY_DEST_DIR}
      echo INFO:: set the target destination for binary tar file \(BINARY_TAR_DEST_DIR\) to $NIGHTLY_DEST_DIR
   fi
else 
    # this is a stable release

    echo ============= This is a stable build ==============

    ${WGETO} -O ${AUTOBUILD_SOURCES}/index.html -o ${AUTOBUILD_SOURCES}/wget-e.s.p.log $release_server_dir/
    echo examining release server files ${AUTOBUILD_SOURCES}/index.html
    echo ========== awk results:
    awk  ' /a href=.*.tar.gz/ {f=$2; split(f, arr, "\""); file=arr[2]; gsub(".tar.gz", "", file); print file}' \
       ${AUTOBUILD_SOURCES}/index.html
    echo ==== with tail ==========
    awk  ' /a href=.*.tar.gz/ {f=$2; split(f, arr, "\""); file=arr[2]; gsub(".tar.gz", "", file); print file}' \
       ${AUTOBUILD_SOURCES}/index.html | tail -1
    echo =========== from ${AUTOBUILD_SOURCES}/index.html 
    cat ${AUTOBUILD_SOURCES}/index.html 
    echo ==============
    coot_version=$(awk  ' /a href=.*.tar.gz/ {f=$2; split(f, arr, "\""); file=arr[2]; gsub(".tar.gz", "", file); print file}' \
       ${AUTOBUILD_SOURCES}/index.html | tail -1)
    if test -z "$coot_version" ; then
       # maybe it wasn't GNU awk (we can't sort the associative array), this will pick a "random" arry key -> coot_version
       coot_version=$(awk  ' /.*a href=/ {f=$2; split(f, arr, "\""); file=arr[2]; gsub(".tar.gz", "", file); files[file]=1; } END { for (file in files) { final=file } ; print final } ' \
        ${AUTOBUILD_SOURCES}/index.html | tail -1)
    fi
    echo coot_version $coot_version

    BINARY_TAR_DEST_DIR=$STABLE_DEST_DIR
    mkdir -p ${BINARY_TAR_DEST_DIR}
fi

echo INFO:: binary tar destination dir: BINARY_TAR_DEST_DIR is $BINARY_TAR_DEST_DIR

####################################################
# exit
####################################################



echo coot_version_pre is $coot_version_pre
echo build_coot_prerelease: $build_coot_prerelease
echo release_server_dir $release_server_dir 
echo coot_version $coot_version


# set the build prefix for installed stuff.  Put everything in the
# pre-release directory if we are building a pre-release.
# (Perhaps this bit of code should go down lower, where we test 
# build_coot_prerelease again
#
# we need install_top_dir because we use it to copy over coot.py 
# to the install python directory.
#
if [ "$build_coot_prerelease" = 1 ] ; then 
    if [ "$coot_prerelease_exists" = 1 ] ; then 
      generic_prefix="--prefix=${AUTOBUILD_INSTALLED}-pre-release-gtk2${build_type} ${config_extras:-}"
      install_top_dir=${AUTOBUILD_INSTALLED}-pre-release-gtk2${build_type}
    else 
      # don't use pre-release
      generic_prefix="--prefix=${AUTOBUILD_INSTALLED}-gtk2${build_type} ${config_extras:-}"
      coot_prefix="$generic_prefix"
      install_top_dir=${AUTOBUILD_INSTALLED}-gtk2${build_type}
    fi
else 
   # not pre-release
   generic_prefix="--prefix=${AUTOBUILD_INSTALLED}-gtk2${build_type} ${config_extras:-}"
   install_top_dir=${AUTOBUILD_INSTALLED}-gtk2${build_type}
   coot_prefix="$generic_prefix"
fi
# we shall include python here too
# but first define the versions
#python_version=python2.5
#pver=2.5.2
# no 2.6.7 for windows yet, need 2.6 because of gtk 2.16, cos of gtkglext
#pver=2.6.7
pver=2.7.15
pver_short=${pver%.*}
# remove the "." to make more Windows compliant
python_version=python${pver_short//./}

PATH=$install_top_dir/bin:$install_top_dir/${python_version}:$PATH
echo the path before testing for installed modules is $PATH

installed_check_maybe_prefix=
if [ "$check_dependencies_in_install_only" = 1 ] ; then
   installed_check_maybe_prefix=$install_top_dir/bin/
fi

# Remove install_top_dir if exists and flag set to do so
# start from scratch
wincoot_exe=WinCoot-${wincoot_version}.exe
if [ "$make_from_scratch" = "yes" ] ; then
    if [ -e "$install_top_dir" ] ; then
        echo clean out everything from $install_top_dir
        rm -fr $install_top_dir
    fi
fi

# we need to export this for net-http, because it doesn't set
# variables from configure, we rely on a shell (environment) variable.
export install_top_dir

echo testing for install_top_dir: "$install_top_dir"
if [ ! -e "$install_top_dir" ] ; then
	echo $install_top_dir does not exist
	echo making directory $install_top_dir
	mkdir -p $install_top_dir
	if [ $? -ne 0 ] ; then
		echo DISASTER: $install_top_dir does not exist and no way
		echo to make it.
	        my_exit 2
	fi
else
	echo INFO:: $install_top_dir exists already.
fi
echo done testing for $install_top_dir

if [ ! -e "$install_top_dir/lib" ] ; then
	echo making "$install_top_dir/lib"
	mkdir -p "$install_top_dir/lib"
        if [ $? -ne 0 ] ; then
                echo DISASTER: $install_top_dir/lib cannot be created
                echo to make it.
                my_exit 2
        fi
fi
#
# append or set LD_LIBRARY_PATH.
#
# this can be problematic for a distributable tar build because this can cause linkage
# against ccp4's libxml2! Hmm!
# 
#
if [ -z "$LD_LIBRARY_PATH" ] ; then
    LD_LIBRARY_PATH=$install_top_dir/lib
    export LD_LIBRARY_PATH
else
    LD_LIBRARY_PATH=$install_top_dir/lib:$LD_LIBRARY_PATH
    export LD_LIBRARY_PATH
fi



#for Macs:
if test "$OS" = "Darwin" ; then
   if [ -z "$DYLD_LIBRARY_PATH" ] ; then
      # DYLD_LIBRARY_PATH=$install_top_dir/lib
      # export DYLD_LIBRARY_PATH
      :
   else
      #DYLD_LIBRARY_PATH=$install_top_dir/lib:$DYLD_LIBRARY_PATH
      #export DYLD_LIBRARY_PATH
      :
   fi
fi

#
# IRIX64 (on batman at least) does not seem to use LD_LIBRARY_PATH, 
# it uses, instead, LD_LIBRARYN32_PATH.  So we set that for all
# systems, hoping that it won't do any harm on other systems.
#
# This surely is no longer used - PE 20130909
# LD_LIBRARYN32_PATH=$LD_LIBRARY_PATH
# export LD_LIBRARYN32_PATH



# ccp4_system_type can be one of the following 
# irix irix64 sunos sunos64 aix hpux osf1 linux freebsd
# linux_compaq_compilers linux_intel_compilers generic Darwin
# ia64_linux_intel Darwin_ibm_compilers linux_ibm_compilers

ccp4_system_type="$OS"
if test "$OS" = Linux ; then
   ccp4_system_type=linux
else
   if test "$OS" = IRIX64 ; then
       ccp4_system_type=irix64
   else 
      if test "$OS" = IRIX ; then
          ccp4_system_type=irix
      else
         if test "$OS" = Darwin ; then
            ccp4_system_type=Darwin
	 else
	    case "$OS" in 
               MINGW*) 
	         # not sure if really needed later?!
	         ccp4_system_type=MinGW
            esac
         fi
      fi
   fi
fi
echo ccp4_system_type $ccp4_system_type


# check for swig
#
echo this swig:
which swig > /dev/null
have_swig=$?
if [ $have_swig = 0 ] ; then
    swig -version
    if [ "$architecture" = x86_64 ] ; then 
       swig_version=`swig -version | awk 'NF { print $NF; exit }'`
       if [ "$swig_version" = 1.3.34 ] ; then
          echo oops this swig is broken.  Need to upgrade to 1.3.36
          my_exit 2
       else 
          echo system has swig.  Good.
       fi
    else 
       echo system is not 64 bit, no problems swig 1.3.34
    fi
else
   echo swig required - not found.
   my_exit 2
fi

# Hope this doesnt mess things on windows?!
# clean up old test status
date_str=`date +"%a_%d_%b_%H:%M"`
echo build-in-progress @$date_str > $LOGS/gtk2$build_type-build-status
echo waiting for build... > $LOGS/gtk2$build_type-test-status

# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
#                                which components?
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
#
# Often there are components provided by the operating system or optional 
# installs thereof.
#
build_mmdb=0
build_ssmlib=0
build_fftw=0
build_clipper=0
build_guile=0
build_guile_www=0
build_guile_gui=0
build_libtool=0
build_net_http=0
build_gsl=0
# build_libungif=0
# build_libtiff=0
# build_libjpeg=0
# build_libpng=0
# build_imlib=0
# build_gtk_canvas=0
build_goocanvas=
build_python=
build_pygobject=
build_guile_gtk=
build_gtkglext=
#build_freeglut=0
build_glib=
#build_readline=
build_curl=
#build_libidn=
build_guile_lib=0
build_gettext=0
build_gtk=0
#gnome_canvas????
# for windows
build_glob=


# In Gtk2, we presume that glib, gtk2 and gnomecanvas are available.  
# We shall test for these, but not build them.

# Where might the "system" components be?
#
non_standard_dir_list="/usr/freeware /sw /opt/gnome $install_top_dir"
dir_list="/usr /usr/X11R6 /usr/local $non_standard_dir_list"

# fftw
# We can eventually get fancy on this... but then clipper configure
# needs changing.
# The test is -n, i.e. a non-zero string length to build things.
#
# We need to test the $AUTOBUILD_INSTALLED directory for fftw because any
# other place could quite well have the fftw that is compiled with doubles.
#
if test -e $install_top_dir/include/fftw.h ; then
   echo installation has fftw
   build_fftw=
fi

if test -n "$build_fftw" ; then
   echo fftw should be built
   build_fftw=1
fi


if [ -e $install_top_dir/include/curl/curl.h ] ; then
   echo installation has curl/libcurl 
else
   echo curl should be built
   build_curl=1
fi



# test for pkg-config
if type pkg-config ; then
   if pkg-config --atleast-pkgconfig-version 0.16 ; then
      build_pkg_config=
      echo pkg-config is new enough `pkg-config --version`
   else 
      build_pkg_config=1
      echo pkg-config should be built \(but won\'t be\).
   fi
else
   echo pkg-config doesn\'t exist.
   echo so should be build
   build_pkg_config=1
fi

# This allows standard pkg-config to find gtkglext and several other things.
# PKG_CONFIG_PATH=$install_top_dir/lib/pkgconfig:/usr/lib/pkgconfig
# but we dont want to do this and only get the newly installed components
PKG_CONFIG_PATH=$install_top_dir/lib/pkgconfig
export PKG_CONFIG_PATH
echo  PKG_CONFIG_PATH is $PKG_CONFIG_PATH

# Do we have freetype2?  cairo depends on it.
if pkg-config freetype2 ; then
   build_freetype2=
   echo system/installation has freetype2
else 
   echo freetype2 should be built
   build_gtk=2
   build_freetype2=1
   build_cairo=1
   build_pycairo=1
fi

# Do we have fontconfig?  cairo depends on it.
if test -z "$build_freetype2" ; then 
   if pkg-config fontconfig ; then
      build_fontconfig=
     echo system/installation has fontconfig
   else 
      echo fontconfig should be built
      build_gtk=2
      build_fontconfig=1
      build_cairo=1
      build_pycairo=1
   fi
else 
   echo no freetype, fontconfig should be built too.
   build_gtk=2
   build_fontconfig=1
   build_cairo=1
   build_pycairo=1
fi

# gtk 2.10.x says that it needs atk >= 1.9.0 
if pkg-config --atleast-version=1.22 atk ; then
    echo atk is up to date
    build_atk=
else
    echo atk should be built
    build_gtk=2
    build_atk=1
fi

if pkg-config --atleast-version=2.18.0 glib-2.0 ; then
   # have glib
   echo glib is up to date
   build_glib=
else
   echo glib is not up to date, rebuild glib - maybe.
   build_gtk=2
   build_glib=1
fi

# Pango depends on cairo.
# 
if pkg-config --atleast-version=1.8.1 cairo ; then
   # have cairo
   echo cairo is up to date
   build_cairo=
else
   echo cairo is not not up to date, rebuild gtk and friends
   build_pango=1
   build_cairo=1
   build_gtk=1
fi

# pango version 1.12 is what gtk2+ 2.10.14 needs
if [ "$build_pango" != 1 ] ; then 
   if pkg-config --atleast-version=1.12 pango ; then
       echo pango is up to date
       build_pango=
   else
       echo build pango and friends
       build_pango=1
       build_gtk=2
   fi
fi

# Test the output of pkg-config gtk+-2.0 for recent enough gtk. 
# If not, then build it yourself.
# 
# Experiment, to force bragg3 to compile gtk+2
# 
# was 2.8
needed_gtk_version=2.14
#
pkg-config --atleast-version=$needed_gtk_version gtk+-2.0
gtk_pkg_config_status=$?
if [ "$gtk_pkg_config_status" = 0 ] ; then 
   build_cairo=
   if [ "$build_gtk" != 2 ] ; then
      build_gtk=
   fi
   echo :::::::: gtk version is at least $needed_gkt_version
   echo :::::::: gtk version is `pkg-config --modversion gtk+-2.0`
else 
   # no recent/good gtk
   echo :::::::: gtk and dependencies need to be built
   build_gtk=1
   build_gettext=1
fi 




# freeglut
# for dir in ${dir_list} ; do
if test -e ${install_top_dir}/include/GL/freeglut_std.h ; then
   echo installation has Freeglut
   build_freeglut=
   glut_prefix="--with-glut-prefix=${install_top_dir}"
else
   #test for normal glut
   if test -e ${install_top_dir}/include/GL/glut.h ; then
	echo installation has glut
	glut_prefix="--with-glut-prefix=${install_top_dir}"
	build_freeglut=
   else
   	build_freeglut=1
   fi
fi
# done
if test -n "$build_freeglut" ; then
   echo freeglut should be built
   build_freeglut=1
   glut_prefix="--with-glut-prefix=$install_top_dir"
fi

build_libtool=1
if test -e ${install_top_dir}/lib/libltdl.dll.a ; then
    build_libtool=
fi
if test -z "$build_libtool" ; then
    echo installation has libtool
else 
    echo libtool should be built
fi

build_gmp=1
if test -e ${install_top_dir}/lib/libgmp.dll.a ; then
    echo installation has gmp
    build_gmp=
else 
    echo gmp should be built
fi


build_readline=1
#
# guile dependency readline.  chihiro has bad build in
# guile-1.6.7/guile-readline/readline.c:107 'rl_pending_input' undeclared
# So installation needs to build readline (sigh).
#
if test -e ${install_top_dir}/include/readline/chardefs.h ; then
    build_readline=
fi

if test -z "$build_readline" ; then
    echo installation has readline
else 
    echo readline needs to be built
fi


# Darwin currently has guile-1.6 and guile (which is an older version)
# we want to use guile-1.6 if it exists.

# This need to be fixed for Macs I guess.  We need 1.8.3 not 1.6
#
# echo guile-1.6-config will fail on non-fink non-mac systems
# guile-1.6-config --version
# if test $? = 0 ; then
#    echo linking in fink 1.6 guile...
#    rm -f $install_top_dir/bin/guile
#    rm -f $install_top_dir/bin/guile-config
#    rm -f $install_top_dir/bin/guile-snarf
#    ln -s /sw/bin/guile-1.6        $install_top_dir/bin/guile
#    ln -s /sw/bin/guile-1.6-config $install_top_dir/bin/guile-config
#    ln -s /sw/bin/guile-1.6-snarf  $install_top_dir/bin/guile-snarf
# fi

echo atempting to run installed guile-config \(this may fail, that\'s OK\).
$install_top_dir/bin/guile-config --version
if test $? != 0 ; then
   echo guile should be built
   build_guile=1
else 
    # We have a seen a situation somehow where bin/guile-config is installed 
    # but include/libguile.h is not.  Strange.  Let's test for libguile.h too.
    if test -e $install_top_dir/include/libguile.h ; then
	echo installation has guile
	build_guile=
    else 
       echo no include/libguile.h. guile     should be built
       echo no include/libguile.h. guile-gtk should be built
       build_guile_gtk=1
       build_guile=1
    fi
fi

# guile-gui
if test -f $install_top_dir/share/guile/gui/paren-match.scm ; then
    echo installation has guile-gui
    build_guile_gui=
else
    echo guile-gui needs to be installed
    build_guile_gui=1
fi


# guile-lib
if test -f $install_top_dir/share/guile/site/sxml/simple.scm ; then
    echo installation has guile-lib
    build_guile_lib=
else
    build_guile_lib=1
    echo guile-lib needs to be installed
fi



# do we have greg?

# LD_LIBRARY_PATH has been set by now
echo testing for greg using `which guile`
# may fail on windows, but ok
guile -c '(use-modules (ice-9 greg))'
status=$?
echo guile greg status $status
if test $status = 0 ; then
   echo installation has greg
   build_greg=
else
   echo greg should be built
   build_greg=1
fi

# ============= python ================
#
# python_version is the filename of the python executable.  For python
# 2.5.1 it is python2.5, not python2.5.1
#

python -V
if test $? != 0 ; then
   echo python should be built
   build_python=1
   build_pygtk=1
   build_pycairo=1
   build_pygobject=1
   if [ $build_enhanced_ligand = 1 ] ; then
       build_numpy=1
       build_six=1
       build_qed=1
   fi
else
   python_version_installed=`python -V 2>&1`
   python_target_version="Python $pver"

   case "$python_version_installed" in 
       "$python_target_version") 
         echo installation has python, $python_version_installed
         which python
         # maybe have to copy it!!!
         if test -e $install_top_dir/$python_version/include/Python.h ; then
             # python seems to be in the correct place
             build_python=
             copy_python=
         else
             # copy it
             build_python=1
             copy_python=1
         fi
         ;;
       *)
         echo python $python_version_installed installed but not up to date...
         echo python  should be built
         build_python=1
         build_pygobject=1
         build_pycairo=1
         build_pygtk=1
         if [ $build_enhanced_ligand = 1 ] ; then
             build_numpy=1
             build_six=1
             build_qed=1
         fi
         ;;
   esac
fi


# test for pygobject
if test -z "$build_pygobject" ; then
   if test -e $install_top_dir/$python_version/include/pygtk-2.0/pygobject.h ; then
      echo installation has pygobject
      build_pygobject=
   else 
      echo pygobject NOT exists, pygobject should be built
      build_pygobject=1
      build_pycairo=1
      build_pygtk=1
   fi      
fi

# test for pycairo
if test -z "$build_pycairo" ; then
   if test -e $install_top_dir/$python_version/include/pycairo/pycairo.h ; then
      echo installation has pycairo
      build_pycairo=
   else 
      echo pycairo NOT exists, pycairo should be built
      build_pycairo=1
      build_pygtk=1
   fi      
fi

# test for pygtk
if test -z "$build_pygtk" ; then
   if test -e $install_top_dir/$python_version/Lib/site-packages/gtk-2.0/gtk/keysyms.py ; then
      echo pygtk keysyms exists, no build pygtk
   else 
      echo pygtk keysyms NOT exists, pygtk should be built
      build_pygtk=1
   fi      
fi

# test for numpy
if test -z "$build_numpy" ; then
   if test -e $install_top_dir/$python_version/Lib/site-packages/numpy/version.py ; then
      echo numpy version exists, not build numpy
      build_numpy=
   else
      echo numpy version NOT exists, numpy should be built
      build_numpy=1
   fi
fi

# test for six
if test -z "$build_six" ; then
   if test -e $install_top_dir/$python_version/Lib/site-packages/six.py ; then
      echo six version exists, not build six
      build_six=
   else
      echo six version NOT exists, six should be built
      build_six=1
   fi
fi

# test for qed
# test for qed
if test -z "$build_qed" ; then
   if test -e $install_top_dir/$python_version/Lib/site-packages/silicos_it/qed.py ; then
      echo qed version exists, not build qed
      build_qed=
   else
      echo qed version NOT exists, qed should be built
      build_qed=1
   fi
fi

# force the GSL config to be in $install_top_dir, rather than
# potenially getting it from the system
# but does this compile cleanly on Mac OS X?  I've forgotten.
# Perhaps we will need to be more clever and potentially use
# the fink GSL if it is available.
$install_top_dir/bin/gsl-config --prefix
if test $? != 0 ; then
   echo gsl should be built
   build_gsl=1
else 
   gsl_version=`gsl-config --version`

   needed_gsl_version=1.3

   # tmp value
   build_gsl=`awk -v A=$gsl_version -v N=$needed_gsl_version 'BEGIN{x = (A+0)>(N+0) ? 0 : 1; print x}'`
   echo system/installation has the GSL version $gsl_version
   echo build_gsl is $build_gsl

   if [ $build_gsl = 1 ] ; then
	echo need to build GSL
        build_gsl=1
   else 
	echo GSL is up to date
	# set build_gsl to blank:
	build_gsl=
   fi
fi



# ##############################################################
#   test for GtkGLExt
# ##############################################################

build_gtkglext=1
if [ "$build_gtk" = "" ] ; then 
   if test -e ${install_top_dir}/lib/libgtkglext-win32-1.0.dll.a ; then
      build_gtkglext=
   fi
   if test -z "$build_gtkglext" ; then
      echo installation has gtkglext
   else 
      echo gtkglext should be built
   fi
fi



# ##############################################################
#   test for guile-gtk
# ##############################################################

# guile-gtk, only look in installation, not system.

# if we are not building gtk, perhaps we should not build
# guile-gtk also?
if test -e "${install_top_dir}/include/guile-gtk.h" ; then
   echo installation has guile-gtk
   if [ "$build_guile" != 1 ] ; then
      build_guile_gtk=
   else
      echo guile needs building, so guile-gtk needs building.
      build_guile_gtk=1
   fi
else
   echo installation does not have guile-gtk
   build_guile_gtk=1
fi

if test -n "${build_guile_gtk}" ; then
   echo guile-gtk.h not found, guile-gtk should be built
   build_guile_gtk=1
else
   echo guile-gtk should not be built
fi

# ##############################################################
#   test for gnomecanvas
# ##############################################################

# test for gnomecanvas here
if [ "$build_gtk" = "" ] ; then 
   pkg-config --modversion libgnomecanvas-2.0
    if [ $? = 0 ] ; then 
       gnome_canvas_result=`pkg-config --modversion libgnomecanvas-2.0`
       case ${gnome_canvas_result} in
           2.*) 
            echo system has libgnomecanvas-2.0
            ;; 
           *)
             echo system does not have libgnomecanvas-2.0
             my_exit 2
             ;; 
       esac
   else 
      echo pkg-config does not find libgnomecanvas-2.0.  Try to build.
      build_libgnomecanvas=1
   fi
else 
   echo gnomecanvas need to be built
   build_libgnomecanvas=1
fi

# ##############################################################
#   test for goocanvas
# ##############################################################

if [ "$build_goocanvas" = "" ] ; then

    # has it been installed?
    #
    if [ -e "${install_top_dir}/include/goocanvas-1.0.0/goocanvas/goocanvaswidget.h" ] ; then
        build_goocanvas=no
        goocanvas_args="--with-goocanvas-prefix=$install_top_dir"
    else
        build_goocanvas=yes
        goocanvas_args="--with-goocanvas-prefix=$install_top_dir"
    fi

    # is it compilable? (do we have the right gtk (etc) version?)
    # this is nonsense to test before we have installed the other things. Since
    # we are using binaries on windows, who cares. We hope that the
    # dependencies will be there, so comment out this nonsense
    #
    #if [ "$build_goocanvas" = "yes" ] ; then
    #    if pkg-config gtk+-2.0 --atleast-version 2.12 ; then
    #        echo goocanvas: recent enough gtk+ version
    #        if pkg-config cairo --atleast-version 1.4 ; then
    #            echo goocanvas: recent enough cairo version
          # yes, compilable
    #            goocanvas_args="--with-goocanvas-prefix=$install_top_dir"
    #        else
    #            echo goocanvas: Cairo is too old.  Goocanvas needs cairo 1.4 or later. You have:
    #            pkg-config cairo --modversion
    #            build_goocanvas=no
    #        fi
    #    else 
    #        echo goocanvas: gtk+-2.0 too old.  Goocanvas needs 2.12 or later. You have:
    #        pkg-config gtk+-2.0 --modversion
    #        build_goocanvas=no
    #    fi
    #fi
fi
echo goocanvas:  goocanvas_args set to $goocanvas_args


# test for mmdb: Does mmdb_model.h exist, and if it does, does it
# contain MMDBF_IgnoreHash.  If not, then build mmdb.
#
# CCP4 mmdb installs in the include/mmdb2 directory, 
#
if test -e "${install_top_dir}/include/mmdb2/mmdb_model.h" ; then
    build_mmdb=
else
    echo installation has no mmdb, build mmdb.
    build_mmdb=1
fi



ssm_include_dir=ssm
if [ -e $install_top_dir/include/$ssm_include_dir/ssm_align.h ] ; then
   if [ "$build_mmdb" = 1 ] ; then
      build_ssmlib=1
   else 

      # do we have SSM version 1.4 or later?
      if grep --silent "MINOR_VERSION = [4-9]" $install_top_dir/include/$ssm_include_dir/ssm_defs.h ; then
         echo SSM is found.
         build_ssmlib=
      else
         echo we need a newer SSM.
         build_ssmlib=1
      fi
   fi
else
   echo SSM not found - needs to be built
   build_ssmlib=1
fi


# clipper depends on mmdb, so if mmdb was built, then so must clipper be.
# likewise for fftw.
#
build_clipper=1
if [ -z "$build_mmdb" ] ; then
    # we potentially can pass the building of clipper:
    echo INFO:: shall we build clipper: mmdb not to be built
    if [ -z "$build_fftw" ] ; then 
       echo INFO:: shall we build clipper: fftw not to be built
       # test for new ccp4-based clipper (for mtz and maps)
       if [ -e $install_top_dir/include/clipper/ccp4/ccp4_mtz_io.h ] ; then
          echo $install_top_dir/include/clipper/ccp4/ccp4_mtz_io.h exist
          if [ -e $install_top_dir/include/clipper/contrib/sfscale.h ] ; then
             echo $install_top_dir/include/clipper/contrib/sfscale.h exist
	     build_clipper=
          else
            echo $install_top_dir/include/clipper/contrib/sfscale.h not exist, building clipper
  	     build_clipper=1
          fi
       else 
          echo $install_top_dir/include/clipper/ccp4/ccp4_mtz_io.h not exist, building clipper
       fi
    fi
else
   echo mmdb needs to be built, so clipper needs building.
fi

# shall we build libccp4c?
if [ -e $install_top_dir/lib/libccp4c.la ] ; then
    # 20170925 test for the pkg-config file
    if [ -e $install_top_dir/lib/pkgconfig/libccp4c.pc ] ; then
        # no need to rebuild
        build_ccp4c=
    else 
        build_ccp4c=1
    fi
else
    build_ccp4c=1
fi

# test for glob
if [ -e $install_top_dir/include/glob.h ] ; then
   # have glob, but do we need shared installation?
   build_glob=
   if [ $build_shared = 1 ] ; then
     if [ -e $install_top_dir/bin/libglob.dll ] ; then
       build_glob=
     else
       build_glob=1
     fi
   fi
else
   build_glob=1
fi


# test for boost and rdkit
if [ $build_enhanced_ligand = 1 ]  ; then
    if [ -n "$build_boost" ] ; then
        if [ -e $install_top_dir/include/boost/version.hpp ] ; then
          echo $install_top_dir/include/boost/version.hpp exists not building boost
	      build_boost=
        else
            echo $install_top_dir/include/boost/version.hpp not exist, building boost
  	        build_boost=1
        fi
    fi
    if [ -n "$build_rdkit" ] ; then
        if [ -e $install_top_dir/include/rdkit/RDGeneral/versions.h ] ; then
          echo $install_top_dir/include/rdkit/RDGeneral/versions.h exists not building rdkit
	      build_rdkit=
        else
            echo $install_top_dir/include/rdkit/RDGeneral/versions.h not exist, building rdkit
  	        build_rdkit=1
        fi
    fi
else
   echo No LE version, so no boost and rdkit
fi


# Here we can force the building of clipper because we don't
# know if the dependency libccp4c.la was from 6.0 or 5.0.2
# But, let's not do that any more.
# build_clipper=
# build_ccp4c= 

# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
#                                build components
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
#

#
# libccp4: (not fortran)
if test -n "$build_ccp4c" ; then 
    echo BUILDING: libccp4
    libccp4_version=6.5.1
    # ${WGET} http://www.ysbl.york.ac.uk/~emsley/software/extras/libccp4c-5.0.2-ysbl-2.tar.gz
    # ${WGET} http://www.ysbl.york.ac.uk/~emsley/software/extras/libccp4c-5.0.2-ysbl-3.tar.gz
    #${WGET} http://www.ysbl.york.ac.uk/~emsley/software/extras/martyn-extras.tar.gz
    #${WGET} http://lmb.bioch.ox.ac.uk/coot/software/extras/libccp4c-5.0.2-ysbl-3.tar.gz
    #${WGET} http://lmb.bioch.ox.ac.uk/coot/software/extras/martyn-extras.tar.gz
    #${WGET} http://lmb.bioch.ox.ac.uk/coot/software/extras/ccp4-libs-underlay-2.tar.gz
    # ${WGET} $extras_place/libccp4c-5.0.2-ysbl-3.tar.gz
    # ${WGET} $extras_place/martyn-extras.tar.gz
    # ${WGET} $extras_place/ccp4-libs-underlay-2.tar.gz
    # Dont need patch any more. Great!
    # ${WGET} http://www.ysbl.york.ac.uk/~lohkamp/software/extras/ccp4_library_utils.c.patch
    # ${WGET} ftp://ftp.ccp4.ac.uk/opensource/libccp4-$libccp4_version.tar.gz
    ${WGET} $extras_place/libccp4-$libccp4_version.tar.gz
    ( 
    date
    gzip -dc ${AUTOBUILD_SOURCES}/libccp4-$libccp4_version.tar.gz | tar xf -
    cd libccp4-$libccp4_version
    ./configure $generic_prefix $shared_static_flag --disable-fortran
    $MAKE
    $MAKE install
    ) 2>&1 >  $HOSTLOGDIR/01-libccp4.txt 
else 
    echo not building libccp4:
fi
#
# mmdb
#
#
# mmdb
#
if test -n "$build_mmdb" ; then
   echo BUILDING mmdb:
#
# mmdb_version=1.0.10.  Not yet.
# mmdb_version=1.0.8-ysbl-3
mmdb_version=1.11
mmdb_version=1.12
mmdb_version=1.19
mmdb_version=1.21
mmdb_version=1.22
mmdb_version=1.23
mmdb_version=1.23.2
mmdb_version=1.24
mmdb_version=1.24.2
mmdb_version=1.25.0
mmdb_version=1.25.2
mmdb_version=1.25.3
mmdb_version=2.0.1
mmdb_version=2.0.2
mmdb_version=2.0.5
mmdb_version=2.0.11
mmdb_version=2.0.16
mmdb_version=2.0.19
mmdb_version=2.0.20
mmdb_version=2.0.22
#mmdb_server_dir=ftp://ftp.ccp4.ac.uk/opensource
mmdb_server_dir=$win_extras_place
mmdb_server_dir=$extras_place
echo ${WGET} $mmdb_server_dir/mmdb2-$mmdb_version.tar.gz
${WGET} $mmdb_server_dir/mmdb2-$mmdb_version.tar.gz
${WGET} $win_extras_place/mmdb_io_file.cpp.patch

(
date
gzip -dc ${AUTOBUILD_SOURCES}/mmdb2-$mmdb_version.tar.gz | tar xf -
echo gzip -dc ${AUTOBUILD_SOURCES}/mmdb2-$mmdb_version.tar.gz
cd  mmdb2-$mmdb_version
pwd
patch -p0 <${AUTOBUIILD_SOURCES}/mmdb_io_file.cpp.patch
./configure $generic_prefix $shared_static_flag
$MAKE
$MAKE install
) > $HOSTLOGDIR/02-mmdb.txt 2>&1
else
   echo not building mmdb:
fi


if test -n "$build_ssmlib" ; then 

   echo BUILDING SSM:
#
# ssm_version=0.0-pre-2-ysbl
ssm_version=1.4
#${WGET} http://lmb.bioch.ox.ac.uk/coot/software/extras/SSMlib-$ssmlib_version.tar.gz
#${WGET} http://lmb.bioch.ox.ac.uk/coot/software/extras/SSMlib-$ssmlib_version.tar.gz
# ${WGET} $extras_place/SSMlib-$ssmlib_version.tar.gz
# ${WGET} ftp://ftp.ccp4.ac.uk/opensource/ssm-1.3.tar.bz2
# ${WGET} ftp://ftp.ccp4.ac.uk/opensource/ssm-1.3.tar.bz2
${WGET} $extras_place/ssm-$ssm_version.tar.gz
(
date
# gzip -dc ${AUTOBUILD_SOURCES}/SSMlib-$ssmlib_version.tar.gz | tar xf -
gzip -cd ${AUTOBUILD_SOURCES}/ssm-$ssm_version.tar.gz | tar xf -
cd ssm-$ssm_version
# ./configure $generic_prefix --with-mmdb-prefix=$install_top_dir
# grrr PE I agree
./configure $generic_prefix $shared_static_flag CPPFLAGS=-I$install_top_dir/include LDFLAGS=-L$install_top_dir/lib
$MAKE
$MAKE install
) >  $HOSTLOGDIR/02-ssm.txt 2>&1
else 
   echo not building ssm:
fi


# fftw FIXME - use binaries
if test -n "$build_fftw" ; then
    echo BUILDING fftw:
#
#${WGET} http://www.ysbl.york.ac.uk/~emsley/software/fftw-2.1.5.tar.gz
#${WGET} http://www.ysbl.york.ac.uk/~emsley/software/extras/fftw-configure-stuff.tar.gz
${WGET} $extras_place/fftw-2.1.5.tar.gz
${WGET} $win_extras_place/fftw-2.1.5_shared.patch
${WGET} $win_extras_place/fix_shared_makefiles.sh
${WGET} $win_extras_place/fix_libfftw.la.sh
#${WGET} $extras_place/fftw-configure-stuff.tar.gz
(
date
pwd
gzip -dc ${AUTOBUILD_SOURCES}/fftw-2.1.5.tar.gz | tar xf -
#gzip -dc ${AUTOBUILD_SOURCES}/fftw-configure-stuff.tar.gz | tar xf -
# FIXME:: needs some post-processing for dlls
cd fftw-2.1.5
if [ $build_shared = 1 ] ; then
  ./bootstrap.sh
  libtoolize -c -f
fi
./configure $generic_prefix $shared_static_flag --enable-float
if [ $build_shared = 1 ] ; then
  ${AUTOBUILD_SOURCES}/fix_shared_makefiles.sh
  patch -p0 <${AUTOBUILD_SOURCES}/fftw-2.1.5_shared.patch
fi
$MAKE
$MAKE install
)  > $HOSTLOGDIR/03-fftw.txt 2>&1
else
    echo not building fftw:
fi

# # clipper
# #
# #
if test -n "$build_clipper" ; then

    # clipper: we use the ccp4 version of clipper now.
    # (it uses configure, not scons)
    #
    echo BUILDING clipper:
    # clipper_version is for the file name on the server, clipper_dir_version is the directory
    # that files untars into.
    #clipper_version=20ac
    #clipper_version=2.1-081201-ac
    #clipper_version=2.1-090210-ac
    #clipper_version=2.1-090522-ac
    #clipper_version=2.1-091215-ac
    clipper_version=2.1-100511-ac
    clipper_version=2.1
    clipper_version=2.1.20160708
    clipper_version=2.1.20180802
    clipper_dir_version=2.1
    #${WGET} http://www.ysbl.york.ac.uk/~cowtan/clipper/clipper-$clipper_version.tar.gz

    # 20110921 hack in a temporary solution, while Kevin's new clipper
    # is not available yet from his site.
    #${WGET} http://lmb.bioch.ox.ac.uk/coot/software/extras/clipper-2.1-110915-fixup.tar.gz
    # fix threading on windows, i.e. disable
    #${WGET} http://www.ysbl.york.ac.uk/~lohkamp/software/extras/clipper-2.1.thread.patch
    # PE 20110921 hack in a temporary solution, while Kevin's new clipper
    # is not available yet from his site.
    clipper_hack_version=2.1-110915-fixup-2
    clipper_hack_version=2.1-140110-fixup
    #${WGET} $extras_place/clipper-$clipper_hack_version.tar.gz

    # fix mean and lean on windows, i.e. disable
    # ${WGET} http://www.ysbl.york.ac.uk/~lohkamp/software/extras/clipper_win32.patch
    #${WGET} $win_extras_place/clipper_win32.patch

    # now clipper has all the bits.
    # ${WGET} $extras_place/clipper-$clipper_version.tar.gz
    #${WGET} ftp://ftp.ccp4.ac.uk/opensource/clipper-$clipper_version.tar.gz
    ${WGET} $win_extras_place/clipper-$clipper_version.tar.gz

    (
    gzip -dc ${AUTOBUILD_SOURCES}/clipper-$clipper_version.tar.gz | tar xf -
    #mv clipper-$clipper_version clipper-$clipper_dir_version
    cd clipper-$clipper_dir_version
    pwd
    date

    # this seems to have already been applied in 2.1.20180802
    # patch the hkl_data.h header
    # needs testing
    # sed -ibackup -e 's/int i = 0; i < list.size(); i++/unsigned int i = 0; i < list.size(); i++/' clipper/core/hkl_data.h
    
    # make clipper
    echo . ------------------------------------------------------------------------------
    echo . "         clipper                                                            "
    echo . ------------------------------------------------------------------------------
    # BL says:: FIXME
    # do we still need the patch?
    export     CPPFLAGS=-I$install_top_dir/include
    export      LDFLAGS="-Wl,--large-address-aware -L$install_top_dir/lib"
    echo CPPFLAGS $CPPFLAGS
    echo LDFLAGS  $LDFLAGS

    #patch -p0 < ${AUTOBUILD_SOURCES}/clipper_win32.patch
    #patch -p0 < ${AUTOBUILD_SOURCES}/clipper-2.1.thread.patch
    # patch the hkl_data.h header
#    sed -ibackup -e 's/int i = 0; i < list.size(); i++/unsigned int i = 0; i < list.size(); i++/' clipper/core/hkl_data.h

    ./configure --prefix=$install_top_dir \
	--enable-mmdb=$install_top_dir    \
	--enable-ccp4=$install_top_dir    \
	$shared_static_flag  \
	--enable-mmdb    \
	--enable-cif     \
	--enable-ccp4    \
	--enable-minimol \
	--enable-cns     \
       CXXFLAGS="-g -O2 -fno-strict-aliasing"
       # CXXFLAGS="-g -O2 -fno-strict-aliasing -DCLIPPER_DISABLE_THREADS"
       # We have to disable the threading for now, no clean exit from (Win)Coot
       # CXXFLAGS="-g -O2 -fno-strict-aliasing"
       # not need any more ?!
       # CCP4_CXXFLAGS=-I$install_top_dir/include CCP4_LIBS=$install_top_dir/lib/libccp4c.la	\
    # we don't want to make the clipper executables, so let's cd in to the clipper libs and
    # make (just) those.
    # not any more!!! make all!!!
    if [ $build_shared = 1 ] ; then
      ${AUTOBUILD_SOURCES}/fix_shared_makefiles.sh
    fi
    $MAKE
    status=$?
    clipper_status=$status
    if [ "$clipper_status" != 0 ] ; then 
        echo make of clipper failed - exit 2 from internal shell.
        exit 2
    else   
        $MAKE install
    fi

    ) > $HOSTLOGDIR/04-clipper.txt 2>&1

    clipper_build_status=$?
    if [ $clipper_build_status != 0 ] ; then
	echo clipper build failed, exiting
	my_exit 2
    fi

else 
    echo not building clipper:
fi



# freeglut
# we use 'normal' glut 
if test -n "$build_freeglut" ; then
    echo BUILDING freeglut:
#nate's version is not good as it requires 'manual' adjustments to compilation
#${WGET} http://www.xmission.com/~nate/glut/glut-3.7.6-bin.zip
# we get another version instead
#${WGET} http://files.transmissionzero.co.uk/software/development/GLUT/freeglut-MinGW-2.8.1-1.mp.zip
# seems dead, use own
${WGET} $win_extras_place/freeglut-MinGW-2.8.1-1.mp.zip

(
date
pwd
cd $build_dir
7z x -y ${AUTOBUILD_SOURCES}/freeglut-MinGW-2.8.1-1.mp.zip
glut_prefix="--with-glut-prefix=$install_top_dir"
echo INFO:: setting glut_prefix to $glut_prefix
# now move the files to the right place
# maybe can unpack in install_top_dir directly now. Check/FIXME
cd freeglut
mkdir_maybe	$install_top_dir/include/GL
cp include/GL/*.h $install_top_dir/include/GL/
mkdir_maybe	$install_top_dir/bin
cp bin/freeglut.dll	$install_top_dir/bin/
mkdir_maybe	$install_top_dir/lib
cp lib/libfreeglut.a	$install_top_dir/lib/
# and whilst we are here let's get the openGL extensions as well
${WGET} --no-check-certificate https://khronos.org/registry/OpenGL/api/GL/glext.h
${WGET} --no-check-certificate https://khronos.org/registry/OpenGL/api/GL/glxext.h
${WGET} --no-check-certificate https://khronos.org/registry/OpenGL/api/GL/wglext.h
cp ${AUTOBUILD_SOURCES}/glext.h  $install_top_dir/include/GL/
cp ${AUTOBUILD_SOURCES}/glxext.h $install_top_dir/include/GL/
cp ${AUTOBUILD_SOURCES}/wglext.h $install_top_dir/include/GL/
cd ${AUTOBUILD_SOURCES}
) >  $HOSTLOGDIR/05-freeglut.txt 2>&1
else
   echo not building freeglut:
fi


###############################################################################
##########         pkg-config (blimey)                            #############
###############################################################################

if test -n "$build_pkg_config" ; then 
   echo BUILDING pkg-config:
   #
   pkg_config_version=0.26-1
   ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/pkg-config_${pkg_config_version}_win32.zip
   (
   date
   cd $install_top_dir
   7z x -y ${AUTOBUILD_SOURCES}/pkg-config_${pkg_config_version}_win32.zip
   cd -
) > $HOSTLOGDIR/05-pkg-config.txt 2>&1
else 
   echo not building pkg-conifg:
fi



###############################################################################
##########         build gtk and friends                          #############
###############################################################################

# well I guess on windows it's easier to just download the binaries and dev
# packages (in case we need them for later)


# Building of the gtk2 dependencies depend on pkg-config.  
# configure: error: *** pkg-config too old; version 0.16 or better required.
# Get a recent pkg-config here:
# http://pkgconfig.freedesktop.org/releases/pkg-config-0.23.tar.gz


# gtk2 build says that pango depends on cairo:
# checking Pango flags... configure: error:
# *** Pango not found. Pango built with Cairo support is required
# *** to build GTK+. See http://www.pango.org for Pango information.
# 
# so, if we build cairo, we must build pango too


# just to make sure we download in sources
cd ${AUTOBUILD_SOURCES}

if test -n "$build_gtk" ; then 
   echo BUILDING Gtk+-2 and/or dependencies...
   (
   if [ "$build_atk" = 1 ] ; then 
      echo  ======================================================
      echo BUILDING atk binaries
      echo  ======================================================
      atk_major_version=1.32
      atk_version=1.32.0-2
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/atk/${atk_major_version}/atk_${atk_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/atk/${atk_major_version}/atk-dev_${atk_version}_win32.zip
      date
      cd $install_top_dir
      7z x -y ${AUTOBUILD_SOURCES}/atk_${atk_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/atk-dev_${atk_version}_win32.zip
      cd -
   else
      echo not BUILDING atk
   fi


# dont think we really need glitz!?
 
   if [ "$build_glib" = 1 ] ; then
      echo  ======================================================
      echo BUILDING glib binaries and dev
      echo  ======================================================
      glib_major_version=2.28
      glib_version=2.28.8-1
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/glib/${glib_major_version}/glib_${glib_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/glib/${glib_major_version}/glib-dev_${glib_version}_win32.zip
      cd $install_top_dir
      7z x -y ${AUTOBUILD_SOURCES}/glib_${glib_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/glib-dev_${glib_version}_win32.zip
      cd -
      glib_status=0
   else 
      echo not BUILDING glib
   fi

   # cairo(?) dependends on freetype2 (RedHat 8 doesn't have it)
   if [ "$build_freetype2" = 1 ] ; then
      echo  ======================================================
      echo BUILDING freetype2
      echo  ======================================================
      freetype2_version=2.4.10-1
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/freetype_${freetype2_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/freetype-dev_${freetype2_version}_win32.zip
      cd $install_top_dir
      7z x -y ${AUTOBUILD_SOURCES}/freetype_${freetype2_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/freetype-dev_${freetype2_version}_win32.zip
      cd -
   else 
      echo NOT BUILDING freetype2
   fi

   # cairo(?) dependends on fontconfig (include file?) to define `FC_RGBA_UNKNOWN'
   # fontconfig depends on Freetype2 (what fun).
   if [ "$build_fontconfig" = 1 ] ; then
      echo  ======================================================
      echo BUILDING fontconfig and expat
      echo  ======================================================
      fontconfig_version=2.8.0-2
      # we need libexpat for fontconfig
      expat_version=2.1.0-1
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/fontconfig_${fontconfig_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/fontconfig-dev_${fontconfig_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/expat_${expat_version}_win32.zip
      cd $install_top_dir
      7z x -y ${AUTOBUILD_SOURCES}/fontconfig_${fontconfig_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/fontconfig-dev_${fontconfig_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/expat_${expat_version}_win32.zip
      cd -
   else
      echo NOT BUILDING fontconfig
   fi

   if [ "$build_cairo" = 1 ] ; then
      echo  ======================================================
      echo  BUILDING cairo
      echo  ======================================================
      cairo_version=1.10.2-2
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/cairo_${cairo_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/cairo-dev_${cairo_version}_win32.zip
      cd $install_top_dir
      7z x -y ${AUTOBUILD_SOURCES}/cairo_${cairo_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/cairo-dev_${cairo_version}_win32.zip
      cd -
   else
      echo NOT BUILDING cairo
   fi
 
   if [ "$build_pango" = 1 ] ; then
      echo  ======================================================
      echo  BUILDING pango
      echo  ======================================================
      pango_major_version=1.29
      pango_version=1.29.4-1
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/pango/${pango_major_version}/pango_${pango_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/pango/${pango_major_version}/pango-dev_${pango_version}_win32.zip
      cd $install_top_dir
      7z x -y ${AUTOBUILD_SOURCES}/pango_${pango_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/pango-dev_${pango_version}_win32.zip
      cd - 
      pango_status=0
   else
      echo NOT BUILDING pango
   fi

   # librsvg depends on libpng and lib-xml-2, so we shall get these
   if [ "$pango_status" = 0 ] ; then
      echo  ======================================================
      echo  BUILDING libpng, libtiff, and libjpeg
      echo  ======================================================
      libpng_version=1.4.12-1
      libjpeg_version=8-1
      libtiff_version=3.9.2-1
      zlib_version=1.2.5-2
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/libpng_${libpng_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/libpng-dev_${libpng_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/jpeg_${libjpeg_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/libtiff_${libtiff_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/zlib_${zlib_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/zlib-dev_${zlib_version}_win32.zip
      cd $install_top_dir
      7z x -y ${AUTOBUILD_SOURCES}/libpng_${libpng_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/libpng-dev_${libpng_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/jpeg_${libjpeg_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/libtiff_${libtiff_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/zlib_${zlib_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/zlib-dev_${zlib_version}_win32.zip
      cd -
   else
       echo NOT BUILDING libpng
   fi

   if [ "$pango_status" = 0 ] ; then
      echo  ======================================================
      echo  BUILDING libxml2
      echo  ======================================================
      libxml2_version=2.9.0-1
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/libxml2_${libxml2_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/libxml2-dev_${libxml2_version}_win32.zip
      cd $install_top_dir
      7z x -y ${AUTOBUILD_SOURCES}/libxml2_${libxml2_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/libxml2-dev_${libxml2_version}_win32.zip
      cp bin/libxml2-2.dll bin/libxml2.dll
      cd -
   else
       echo NOT BUILDING libxml2
   fi
   

   # and we need libiconv
   if [ "$glib_status" = 0 ] ; then
      echo  ======================================================
      echo  BUILDING libiconv
      echo  ======================================================
      libiconv_version=1.9.1
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/libiconv-${libiconv_version}.bin.woe32.zip
      cd $install_top_dir
      7z x -y ${AUTOBUILD_SOURCES}/libiconv-${libiconv_version}.bin.woe32.zip
      cd -
   else
       echo NOT BUILDING libiconv
   fi



   # cairo depends dependends on librsvg (for testing) otherwise warning.
   # But.  librsvg depends on pango (the pangoft2 part).  This is crazy.
   # But.  cairo depend on librsvg (doesn't it?)
   # Does cairo depend on pango? Yes.
   if [ "$pango_status" = 0 ] ; then
      echo  ======================================================
      echo  BUILDING librsvg and its extras, croco, gsf, bzip2
      echo  ======================================================
      librsvg_major_version=2.32
      librsvg_version=2.32.1-1
      ${WGET} http://ftp.gnome.org/pub/GNOME/binaries/win32/librsvg/${librsvg_major_version}/librsvg_${librsvg_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/GNOME/binaries/win32/librsvg/${librsvg_major_version}/svg-gdk-pixbuf-loader_${librsvg_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/GNOME/binaries/win32/librsvg/${librsvg_major_version}/svg-gtk-engine_${librsvg_version}_win32.zip

      # and we need croco, gsf and bzip for librsvg to run properly
      # Not sure if needed any more. OBS
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/libcroco/0.6/libcroco_0.6.2-1_win32.zip 
      #${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/libgsf/1.14/libgsf-1.14.4.zip
      #${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/libbzip2-1.0.2.zip

      # now need gdk-pixbuf too (not included anywhere else any more)
      # not yet only when using gtk above 2.20/22 or so
      gdk_pixbuf_major_version=2.24
      gdk_pixbuf_version=${gdk_pixbuf_major_version}.0-1
      ${WGET} http://ftp.gnome.org/pub/GNOME/binaries/win32/gdk-pixbuf/${gdk_pixbuf_major_version}/gdk-pixbuf_${gdk_pixbuf_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/GNOME/binaries/win32/gdk-pixbuf/${gdk_pixbuf_major_version}/gdk-pixbuf-dev_${gdk_pixbuf_version}_win32.zip
      cd $install_top_dir
      7z x -y ${AUTOBUILD_SOURCES}/librsvg_${librsvg_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/svg-gdk-pixbuf-loader_${librsvg_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/svg-gtk-engine_${librsvg_version}_win32.zip

      7z x -y ${AUTOBUILD_SOURCES}/libcroco_0.6.2-1_win32.zip
      #7z x -y ${AUTOBUILD_SOURCES}/libgsf-1.14.4.zip
      #7z x -y ${AUTOBUILD_SOURCES}/libbzip2-1.0.2.zip

      7z x -y ${AUTOBUILD_SOURCES}/gdk-pixbuf_${gdk_pixbuf_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/gdk-pixbuf-dev_${gdk_pixbuf_version}_win32.zip
      cd -
      # we shall run gdk-pixbuf-query loader
      # but after we have gtk+!!!
   else
      echo NOT BUILDING librsvg
   fi

   if [ "$build_gtk" = 1 ] ; then
      echo  ======================================================
      echo  BUILDING gtk+2
      echo  ======================================================
      # versions later up to 2.24 may not working with gtkglext on win32!!
      # FIXME check
      # maybe consider bindle download 
      # http://ftp.gnome.org/pub/gnome/binaries/win32/gtk+/2.24/gtk+-bundle_2.24.10-20120208_win32.zip
      gtk2_major_version=2.24
      gtk2_version=2.24.10-1
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/gtk+/${gtk2_major_version}/gtk+_${gtk2_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/gtk+/${gtk2_major_version}/gtk+-dev_${gtk2_version}_win32.zip
      cd $install_top_dir
      7z x -y ${AUTOBUILD_SOURCES}/gtk+_${gtk2_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/gtk+-dev_${gtk2_version}_win32.zip
      cd - 
      # install hicolor theme
      # FIXME - update to 0.15 but uses xz then (check install for it)
      hicolor_version=0.13
      ${WGET} --no-check-certificate http://icon-theme.freedesktop.org/releases/hicolor-icon-theme-${hicolor_version}.tar.gz
      gzip -cd ${AUTOBUILD_SOURCES}/hicolor-icon-theme-${hicolor_version}.tar.gz | tar xf -
      cd hicolor-icon-theme-${hicolor_version}
      ./configure --prefix=$install_top_dir
      $MAKE
      hicolor_status=$?
      if [ "$hicolor_status" != 0 ] ; then 
        echo make of hicolor theme failed
        exit 2
      else   
          $MAKE install
      fi
      cd -
   else
      echo NOT BUILDING gtk2
   fi
   if test -n "$gtk_set_failure" ; then 
      exit 1
   fi

   if [ "$build_gettext" = 1 ] ; then
      echo  ======================================================
      echo  BUILDING gettext
      echo  ======================================================
      gettext_version=0.18.1.1-2
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/gettext-runtime_${gettext_version}_win32.zip
      ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/gettext-runtime-dev_${gettext_version}_win32.zip
      cd $install_top_dir
      7z x -y ${AUTOBUILD_SOURCES}/gettext-runtime_${gettext_version}_win32.zip
      7z x -y ${AUTOBUILD_SOURCES}/gettext-runtime-dev_${gettext_version}_win32.zip
      cd -
   else
      echo NOT BUILDING gettext
   fi
   # run query loader to be able to load svg icons properly
   # FIXME this needs update with new gdk-pixbuf stuff!
   # NEW(?!): gdk-pixbuf.loaders doesnt exist any more use 
   # gdk-pixbuf-query-loaders --update-cache 
   # instead. But how to distribute?! There must be some cache somewhere...
   # it is. Here:
   # ./lib/gdk-pixbuf-2.0/2.10.0/loaders.cache
   # so now the new fix:
   $install_top_dir/bin/gdk-pixbuf-query-loaders.exe --update-cache
   # now we have absolute paths in the file, let's make them relative
   # to avoid running the gdk-pixbuf.loaders during install
   sed -e "s|[^\"]*$install_top_dir|..|" \
     $install_top_dir/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache > tmp.loaders
   mv $install_top_dir/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache $install_top_dir/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache.bak
   mv tmp.loaders $install_top_dir/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache

   ) > $HOSTLOGDIR/06-gtk-prerequisites.txt 2>&1
   if test "$?" != 0 ; then
      echo gtk set failed somewhere
   fi

fi


cd $build_dir
if test -n "$build_gtkglext" ; then
    echo BUILDING gtkglext:
    gtkglext_version=1.2.0
    #${WGET} http://surfnet.dl.sourceforge.net/sourceforge/gtkglext/gtkglext-$gtkglext_version.tar.gz
    ${WGET} http://downloads.sourceforge.net/gtkglext/gtkglext-1.2.0.tar.gz
    # ${WGET} http://www.ysbl.york.ac.uk/~lohkamp/software/extras/gtkglext_configure.patch
    ${WGET} $win_extras_place/gtkglext_configure.patch
    (date
     pwd
     gzip -dc ${AUTOBUILD_SOURCES}/gtkglext-$gtkglext_version.tar.gz | tar xf -
     cd gtkglext-$gtkglext_version
     echo gtk+-2.0 version:
     pkg-config gtk+-2.0 --modversion
     # gtk+ 2.20 needs converting GTK_WIDGET_REALIZED to gtk_widget_get_realised, but 
     # gtk+ 2.18 does not (it fails if we add that patch), so use a simpler one.
     # BL says: for 1.16 we dont need to patch
     if pkg-config gtk+-2.0 --atleast-version 2.18 ; then
        patch_file=gtk-gtkglwidget.c-for-modern-gtk-for-2.18.patch
        echo we have sufficiently new version of gtk+, we need to patch gtkglext with $patch_file
        if pkg-config gtk+-2.0 --atleast-version 2.20 ; then
           patch_file=gtk-gtkglwidget.c-for-modern-gtk.patch
        fi
        #${WGET}   http://lmb.bioch.ox.ac.uk/coot/software/extras/$patch_file
        ${WGET}   $extras_place/$patch_file

        if patch -p0 < ${AUTOBUILD_SOURCES}/$patch_file ; then 
            echo gtkglext patched good.
        else 
            echo gtkglext patch fail.
            my_exit 2
        fi


     else 
        echo version of gtk is old, no need to patch gtkglext.
     fi

     patch -p0 < ${AUTOBUILD_SOURCES}/gtkglext_configure.patch
     echo BL DEBUG PATH before config gtkglext is $PATH
     ./configure --build=i386-pc-mingw32 $generic_prefix
     $MAKE
    status=$?
    if [ "$status" != 0 ] ; then
       echo make of gtkglext failed
    else
       $MAKE install
    fi
    cd -
    ) > $HOSTLOGDIR/06-pre-gtkglext.txt 2>&1
else
    echo not building gtkglext:
fi 

##################### gnomecanvas #####################################

cd ${AUTOBUILD_SOURCES}
## libgnomecanvas
# 
if test -n "$build_libgnomecanvas" ; then
    echo BUILDING libgnomecanvas:
    # we need gail and libartlgpl for gnomecanvas 
    libgnomecanvas_major_version=2.30
    libgnomecanvas_version=2.30.1-1
    libart_version=2.3.21-1
    ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/libgnomecanvas/$libgnomecanvas_major_version/libgnomecanvas_${libgnomecanvas_version}_win32.zip
    ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/libgnomecanvas/$libgnomecanvas_major_version/libgnomecanvas-dev_${libgnomecanvas_version}_win32.zip
    # not needed any more as included in gtk+ now
    ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/libart_lgpl/2.3/libart-lgpl_${libart_version}_win32.zip
    ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/libart_lgpl/2.3/libart-lgpl-dev_${libart_version}_win32.zip
    cd $install_top_dir
(
    7z x -y ${AUTOBUILD_SOURCES}/libgnomecanvas_${libgnomecanvas_version}_win32.zip
    7z x -y ${AUTOBUILD_SOURCES}/libgnomecanvas-dev_${libgnomecanvas_version}_win32.zip
    7z x -y ${AUTOBUILD_SOURCES}/libart-lgpl_${libart_version}_win32.zip
    7z x -y ${AUTOBUILD_SOURCES}/libart-lgpl-dev_${libart_version}_win32.zip
    cd -
) > $HOSTLOGDIR/09-gnomecanvas.txt 2>&1
else
      echo NOT BUILDING libgnomecanvas
fi


echo done with Gtk+-2 and dependencies...

##################### goocanvas #####################################

if [ "$build_goocanvas" != "no" ] ; then
    echo BUILDING goocanvas 
    goocanvas_major_version=1.0
    goocanvas_version=${goocanvas_major_version}.0
    ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/goocanvas/${goocanvas_major_version}/goocanvas-${goocanvas_version}-win32.zip
    ${WGET} http://ftp.gnome.org/pub/gnome/binaries/win32/goocanvas/${goocanvas_major_version}/goocanvas-dev-${goocanvas_version}-win32.zip
    (date
     cd $install_top_dir
     pwd
     7z x -y ${AUTOBUILD_SOURCES}/goocanvas-${goocanvas_version}-win32.zip
     7z x -y ${AUTOBUILD_SOURCES}/goocanvas-dev-${goocanvas_version}-win32.zip
     cd -
    ) > $HOSTLOGDIR/06-pre-goocanvas.txt
else
      echo NOT BUILDING goocanvas
fi

###############################################################################
##########         build python and friends                       #############
###############################################################################

# So that python is found when it is installed:
#
PATH=$install_top_dir/bin:$install_top_dir/$python_version:$install_top_dir/$python_version/Scripts:$PATH
export PATH

# python_version is the filename of the python executable.  For python
# 2.5.1 it is python2.5, not python2.5.1
#

# python
#

cd $install_top_dir
mkdir $python_version
cd $python_version
# get the full directory
py_inst_dir=`pwd -W`
# convert / to \ for windows file names
py_inst_dir=${py_inst_dir//\//\\}
cd $install_top_dir/bin
py_dll_dir=`pwd -W`
py_dll_dir=${py_dll_dir//\//\\}

global_py_inst_dir=${AUTOBUILD_BUILD}/${HOST}/${python_version}
saved_global_py_inst_dir=$global_py_inst_dir
mkdir $global_py_inst_dir
cd $global_py_inst_dir
global_py_inst_dir=`pwd -W`
# convert / to \ for windows file names
# maybe even two
global_py_inst_dir=${global_py_inst_dir//\//\\}
cd -

echo py_inst_dir is: $py_inst_dir
echo py_dll_dir is: $py_dll_dir
echo global_py_inst_dir is :$global_py_inst_dir

if test -n "$build_python" ; then 
    echo BUILDING Python ${pver}:
#
cd ${AUTOBUILD_SOURCES}
echo downloading python from http://www.python.org/ftp/python/$pver/python-$pver.msi
${WGET} --no-check-certificate http://www.python.org/ftp/python/$pver/python-$pver.msi
status=$?
if [ "$status" != 0 ] ; then
   echo problem downloading python
fi
#${WGET} http://www.ysbl.york.ac.uk/~lohkamp/software/extras/unittest_skip_win.patch
(
date
pwd

# New method:
# install python in ${AUTOBUILD_BUILD}/${HOST}
# copy from there, whenever needed.
# Needs occasional uninstall of old pythons....
# 
echo checking for python now

# check if python is installed (correct version)
python_version_installed=`${saved_global_py_inst_dir}/python -V 2>&1`
python_target_version="Python $pver"
echo now compare $python_version_installed with $python_target_version
if [ "$python_version_installed" == "$python_target_version" ] ; then
   echo $python_target_version already installed just copy files
   copy_python=1
else
   # new python needs to be installed, please go ahead!!! put ddl in same dir
   echo msiexec /a python-$pver.msi TARGETDIR=$global_py_inst_dir DLLDIR=$global_py_inst_dir ALLUSERS=1 /qn
   # msiexec //i python-$pver.msi TARGETDIR=$global_py_inst_dir DLLDIR=$global_py_inst_dir ALLUSERS=1 //qn
   msiexec //a python-$pver.msi TARGETDIR=$global_py_inst_dir DLLDIR=$global_py_inst_dir ALLUSERS=1 //qn 
   status=$?
   if [ "$status" != 0 ] ; then
      echo problem installing python
      echo '  may be already installed elsewhere?! But we dont know!?'
      copy_python=1
      my_exit 2
   else
      echo python installation seems successfull, continue
   fi
fi

if test -n "$copy_python" ; then
       # have an installed dll in non-guile dir, so just copy everything over
       echo copy everything over from ${AUTOBUILD_BUILD}/${HOST}
       # what do we need
       # 1. python.xx
       # 2. pythonXX.dll
       # 3. includes (pyg*)
       # 4. pkg-config (pyg*)
       echo copy dir: cp -r ${saved_global_py_inst_dir} ${install_top_dir}
       cp -r ${saved_global_py_inst_dir} ${install_top_dir}
       dll_name=${global_py_inst_dir}/python${pver_short/./}.dll
       echo copy dll: cp $dll_name ${install_top_dir}/bin
       cp $dll_name ${install_top_dir}/bin
       # pygobject
       echo copy pygobject things
       cp -r ${global_py_inst_dir}/include/pygtk-2.0/ $install_top_dir/include/
       cp    ${global_py_inst_dir}/Lib/pkgconfig/pygobject-2.0.pc $install_top_dir/lib/pkgconfig/
       # pycairo
       echo copy pycairo things
       cp -r ${global_py_inst_dir}/include/pycairo/ $install_top_dir/include/
       cp    ${global_py_inst_dir}/Lib/pkgconfig/pycairo.pc $install_top_dir/lib/pkgconfig/
       # pygtk
       echo copy pygtk things
       cp    ${global_py_inst_dir}/Lib/pkgconfig/pygtk-2.0.pc $install_top_dir/lib/pkgconfig/
       copy_python=2
fi
echo $copy_python > $HOME/python_copied.tmp
) >  $HOSTLOGDIR/07-python.txt 2>&1

if [ -e $HOME/python_copied.tmp ] ; then
 if [ $(cat $HOME/python_copied.tmp) == 2 ] ; then
   echo copied python, so dont install pygobject etc.
   build_pygobject=0
   build_pycairo=0
   build_pygtk=0
 fi
 rm $HOME/python_copied.tmp
fi

# to uninstall use:
# msiexec //uninstall python-$pver.msi //qb

# now lets check for pip, if not there install
which pip > /dev/null
have_pip=$?
if [ $have_pip = 0 ] ; then
  echo have pip, we are happy and continue
else
  echo no pip found, so lets see that we can get it
  ${WGET} https://bootstrap.pypa.io/get-pip.py
  python ${AUTOBUILD_SOURCES}/get-pip.py
  # now we shoudl have pip
fi

# We need these otherwise python moans about not finding the libraries.
#
echo setting PYTHONHOME
# first worked somehow with pre-release but should be 2nd
#PYTHONHOME=$install_top_dir/$py_inst_dir
PYTHONHOME=$py_inst_dir
export PYTHONHOME
echo PYTHONHOME is now $PYTHONHOME

# patch the unittest module to allow skipping tests
# not any more (is included)
#echo patching unittest for skipping
#cd ${PYTHONHOME}/Lib
#patch -p0<${AUTOBUILD_SOURCES}/unittest_skip_win.patch
#cd -

echo done python linking.
# now we have "python" in our path - no need to rehash - 
# clever old Bourne shell (or do I mean bash?).
else
    echo not building python:
fi


# building og pygobject, pycairo, and pygtk currently cannot be automated, so we have to press 
# a few buttons
if test -n "$build_pygobject" ; then 
   echo BUILDING pygobject:
   #
   pygobject_version=2.28.3
   #${WGET} http://ftp.gnome.org/pub/GNOME/binaries/win32/pygobject/2.14/pygobject-$pygobject_version.win32-py2.5.exe
   ${WGET} http://ftp.gnome.org/pub/GNOME/binaries/win32/pygobject/2.28/pygobject-${pygobject_version}.win32-py$pver_short.exe
   (
   date
   #msiexec //i pygobject-$pygobject_version.win32-py$pver_short.msi TARGETDIR=$py_inst_dir ALLUSERS=1 //qn
   mkdir ${AUTOBUILD_SOURCES}/pygobject-${pygobject_version}.win32-py$pver_short
   echo do: 7z x -aoa -o${AUTOBUILD_SOURCES}/pygobject-${pygobject_version}.win32-py$pver_short
   7z x -aoa -o${AUTOBUILD_SOURCES}/pygobject-${pygobject_version}.win32-py$pver_short \
       ${AUTOBUILD_SOURCES}/pygobject-${pygobject_version}.win32-py$pver_short.exe
   # now copy files
   cp -r ${AUTOBUILD_SOURCES}/pygobject-${pygobject_version}.win32-py$pver_short/DATA/* \
       $install_top_dir/$python_version/
   cp -r ${AUTOBUILD_SOURCES}/pygobject-${pygobject_version}.win32-py$pver_short/PLATLIB/* \
       $install_top_dir/$python_version/Lib/site-packages/
   $install_top_dir/$python_version/python ${AUTOBUILD_SOURCES}/pygobject-${pygobject_version}.win32-py$pver_short/SCRIPTS/pygobject_postinstall.py -install
   # copy pkgconfig and include files
   mkdir_maybe $install_top_dir/include
   cp -r $install_top_dir/$python_version/include/pygtk-2.0 $install_top_dir/include/
   mkdir_maybe $install_tpo_dir/lib
   cp -r $install_top_dir/$python_version/Lib/pkgconfig $install_top_dir/lib/
) > $HOSTLOGDIR/07-pygobject.txt 2>&1
else 
   echo not building pygobject:
fi


if test -n "$build_pycairo" ; then 
   echo BUILDING pycairo:
   #
   #pycairo_version=1.4.12-1
   pycairo_version=1.8.10
   #${WGET} http://ftp.gnome.org/pub/GNOME/binaries/win32/pycairo/1.4/pycairo-$pycairo_version.win32-py2.5.exe
   ${WGET} http://ftp.gnome.org/pub/GNOME/binaries/win32/pycairo/1.8/pycairo-$pycairo_version.win32-py$pver_short.exe
   (
   date
   #${AUTOBUILD_SOURCES}/pycairo-$pycairo_version.win32-py2.5.exe
   #msiexec //i pycairo-$pycairo_version.win32-py$pver_short.msi TARGETDIR=$py_inst_dir ALLUSERS=1 //qn
   7z x -aoa -o${AUTOBUILD_SOURCES}/pycairo-$pycairo_version.win32-py$pver_short \
       ${AUTOBUILD_SOURCES}/pycairo-$pycairo_version.win32-py$pver_short.exe
   cp -r ${AUTOBUILD_SOURCES}/pycairo-${pycairo_version}.win32-py$pver_short/DATA/* \
       $install_top_dir/$python_version/
   cp -r ${AUTOBUILD_SOURCES}/pycairo-${pycairo_version}.win32-py$pver_short/PLATLIB/* \
       $install_top_dir/$python_version/Lib/site-packages/
   # copy pkgconfig and include files
   cp -r $install_top_dir/$python_version/include/pycairo $install_top_dir/include/
   cp    $install_top_dir/$python_version/Lib/pkgconfig/pycairo.pc $install_top_dir/lib/pkgconfig/
) > $HOSTLOGDIR/07-pycairo.txt 2>&1
else 
   echo not building pycairo:
fi




if test -n "$build_pygtk" ; then 
   echo BUILDING pygtk:
   #
   py_gtk_version=2.24.0
   #${WGET} http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.12/pygtk-$py_gtk_version.win32-py2.5.exe
   #${WGET} http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.16/pygtk-$py_gtk_version.win32-py$pver_short.exe
   ${WGET} http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.24/pygtk-$py_gtk_version.win32-py$pver_short.exe
   (
   date
   #${AUTOBUILD_SOURCES}/pygtk-$py_gtk_version.win32-py2.5.exe
   #msiexec //i ${AUTOBUILD_SOURCES}/pygtk-$py_gtk_version.win32-py$pver_short.msi TARGETDIR=$py_inst_dir ALLUSERS=1 //qn
   # 
   # no msi installer for this version, so we use 7z to unpack and install
   mkdir ${AUTOBUILD_SOURCES}/pygtk-$py_gtk_version.win32-py$pver_short
   echo do: 7z x -aoa${AUTOBUILD_SOURCES}/pygtk-$py_gtk_version.win32-py$pver_short ${AUTOBUILD_SOURCES}/pygtk-$py_gtk_version.win32-py$pver_short.exe
   7z x -aoa -o${AUTOBUILD_SOURCES}/pygtk-$py_gtk_version.win32-py$pver_short \
       ${AUTOBUILD_SOURCES}/pygtk-$py_gtk_version.win32-py$pver_short.exe
   echo do: cp -r ${AUTOBUILD_SOURCES}/pygtk-$py_gtk_version.win32-py$pver_short/DATA/* $install_top_dir/$python_version/
   cp -r ${AUTOBUILD_SOURCES}/pygtk-$py_gtk_version.win32-py$pver_short/DATA/* \
       $install_top_dir/$python_version/
   echo do: cp -r ${AUTOBUILD_SOURCES}/pygtk-$py_gtk_version.win32-py$pver_short/PLATLIB/* $install_top_dir/$python_version/Lib/site-packages/
   cp -r ${AUTOBUILD_SOURCES}/pygtk-$py_gtk_version.win32-py$pver_short/PLATLIB/* \
       $install_top_dir/$python_version/Lib/site-packages/
   echo do: $install_top_dir/$python_version/python ${AUTOBUILD_SOURCES}/pygtk-$py_gtk_version.win32-py$pver_short/SCRIPTS/pygtk_postinstall.py -install
   $install_top_dir/$python_version/python \
       ${AUTOBUILD_SOURCES}/pygtk-$py_gtk_version.win32-py$pver_short/SCRIPTS/pygtk_postinstall.py -install
   # the latter may give error since it cannot make shortcuts

   # copy pkgconfig and include files
   cp -r $install_top_dir/$python_version/include/pygtk-2.0/pygtk \
       $install_top_dir/include/pygtk-2.0/
   cp    $install_top_dir/$python_version/Lib/pkgconfig/pygtk-2.0.pc $install_top_dir/lib/pkgconfig/
) > $HOSTLOGDIR/07-pygtk.txt 2>&1
else 
   echo not building pytgtk
fi

if test -n "$build_numpy" ; then
   echo BUILDING numpy:
   (
   date
   # before using pip we should see that it is installed, otherwise
   # do so. Maybe not the right place here and rather during pythons
   pip install numpy
   # maybe other python things can be installed using pip too?
   status=$?
   if [ $status = 0 ] ; then
       echo numpy seems to have installed ok
   else
       echo issues installing numpy!?
   fi
   ) > $HOSTLOGDIR/07-numpy.txt 2>&1
else
   echo not building numpy
fi

if test -n "$build_six" ; then
   echo BUILDING six:
   (
   date
   pip install six
   status=$?
   if [ $status = 0 ] ; then
       echo six seems to have installed ok
   else
       echo issues installing six!?
   fi
   ) > $HOSTLOGDIR/07-six.txt 2>&1
else
   echo not building six
fi

# Pillow is not available for python2 and msys2 (any more) lets work withou for now
# need to install Pillow (for depictions to work):
# https://files.pythonhosted.org/packages/b3/d0/a20d8440b71adfbf133452d4f6e0fe80de2df7c2578c9b498fb812083383/Pillow-6.2.2.tar.gz

#if [ -e $install_top_dir/lib/python2.7/site-packages/Pillow-6.2.2.dist-info ] ; then
if true ; then
   echo not building Pillow:
else
    pillow_url=https://files.pythonhosted.org/packages/b3/d0/a20d8440b71adfbf133452d4f6e0fe80de2df7c2578c9b498fb812083383/Pillow-6.2.2.tar.gz
    $(WGET) $pillow_url
    if [ -e ${AUTOBUILD_SOURCES}/Pillow-6.2.2.tar.gz ] ; then
        tar xf ${AUTOBUILD_SOURCES}/Pillow-6.2.2.tar.gz
        cd Pillow-6.2.2
        python setup.py build
        python setup.py install
        cd -
    fi
fi


# finally we shall cp (or move?) Lib and DLL directories to bin
# as well as the pkgconfig and include files (..since...)
# N.B. pkgconfig on windows doesnt pick up prefix in *.pc file
# well, actually overwrites it if 'usual' parent path (i.e. lib)
if test -n "$build_python" ; then 
   # echo now copy over DLLs, Lib and $python_version
   # Not any more!?
   #cp -r $global_py_inst_dir/DLLs $install_top_dir/bin
   #cp -r $global_py_inst_dir/Lib  $install_top_dir/bin
   echo cp -r $saved_global_py_inst_dir  $install_top_dir/
   cp -r $saved_global_py_inst_dir  $install_top_dir/
   dll_name=${global_py_inst_dir}/python${pver_short/./}.dll
   echo copy dll: cp $dll_name ${install_top_dir}/bin
   cp $dll_name ${install_top_dir}/bin
fi

# be save and go back to build_dir
cd ${build_dir}

#########
## build BOOST and rdkit
#########
if [ $build_enhanced_ligand = 1 ] ; then
    if test -n "$build_boost" ; then
        echo BUILDING Boost:
        boost_version=1.60.0
        # old wget cant get from sourceforge but new one can. Make sure there
        # is a new one! e.g. https://eternallybored.org/misc/wget/
        ${WGET} --no-check-certificate http://sourceforge.net/projects/boost/files/boost/${boost_version}/boost_${boost_version//./_}.7z
        ${WGET} $win_extras_place/boost_1_60_0.patch
        ${WGET} $win_extras_place/make_boost64.bat
        (
            date
            pwd
            7z x -y ${AUTOBUILD_SOURCES}/boost_${boost_version//./_}.7z
            cd boost_${boost_version//./_}
            patch -p0 < ${AUTOBUILD_SOURCES}/boost_1_60_0.patch
            cmd /c < ${AUTOBUILD_SOURCES}/make_boost64.bat
            cd -
            ) > $HOSTLOGDIR/21-boost.txt 2>&1
    else
        echo not building Boost
    fi

    if test -n "$build_rdkit" ; then
        echo BUILDING rdkit:
        rdkit_version=2018_03_2
        ${WGET} https://github.com/rdkit/rdkit/archive/Release_${rdkit_version}.tar.gz
        # ${WGET} ${win_extras_place}/rdkit_strtok.patch
        (
            date
            pwd
            tmpdir=`pwd`
            gzip -cd ${AUTOBUILD_SOURCES}/Release_${rdkit_version}.tar.gz | tar xf -
            cd rdkit-Release_${rdkit_version}
            # patch -p0 < ${AUTOBUILD_SOURCES}/rdkit_strtok.patch
            export RDBASE=`pwd`
            export PYTHONPATH=$RDBASE
            export PATH=$PATH:$RDBASE/lib
            export PATH=$PATH:$install_top_dir/lib
            mkdir build
            cd build
            cmake -G "MSYS Makefiles" \
                  -DRDK_BUILD_PYTHON_WRAPPERS=ON \
                  -DRDK_BUILD_SLN_SUPPORT=OFF \
                  -DRDK_TEST_MMFF_COMPLIANCE=OFF \
                  -DRDK_BUILD_CPP_TESTS=OFF \
                  -DRDK_BUILD_THREADSAFE_SSS=ON \
                  -DMSVC_RUNTIME_DLL=C:/WINDOWS/System32 \
                  -DRDK_USE_BOOST_SERIALIZATION=OFF \
                  -DBoost_USE_DEBUG_LIBS=OFF \
                  -DBoost_USE_RELEASE_LIBS=ON \
                  -DRDK_INSTALL_INTREE=OFF \
                  -DBUILD_SHARED_LIBS=ON \
                  -DRDK_INSTALL_STATIC_LIBS=OFF \
                  -DRDK_BUILD_CAIRO_SUPPORT=ON \
                  -DCMAKE_INSTALL_PREFIX=$install_top_dir ..
            $MAKE
            $MAKE install
            cd $tmpdir
            ) > $HOSTLOGDIR/22-rdkit.txt 2>&1
    else
        echo not building rdkit
    fi
    # check build necessary!!
fi  # ligand enhanced

# silicos-it's biscu-it
if [ -e $install_top_dir/lib/python2.7/site-packages/silicos_it/descriptors/qed.py ] ; then
   echo not building biscu-it:
else
   echo building QED
   (date
    ${WGET} http://silicos-it.be.s3-website-eu-west-1.amazonaws.com/_downloads/qed-1.0.1.tar.gz
    pwd
    tar xf ${AUTOBUILD_SOURCES}/qed-1.0.1.tar.gz
    cd qed-1.0.1
    python setup.py install
    cd -
   ) > $HOSTLOGDIR/19-biscu-it.txt 2>&1
fi

# Now we need:
#  * guile
#  * guile-www
#  * guile-gtk
#  * guile-gui
#  * gsl



###############################################################################
##########         build guile and friends                        #############
###############################################################################

# only if we really want to
if [ "$ENABLE_GUILE_COOT" = "yes" ] ; then

cd $build_dir
if test -n "$build_gmp" ; then
    echo BUILDING gmp:
    gmp_version=4.2.4
    # FIMXE, maybe update to 5.1.2
    ${WGET} http://www.mirrorservice.org/sites/ftp.gnu.org/gnu/gmp/gmp-$gmp_version.tar.gz
    (date
     pwd
     gzip -dc ${AUTOBUILD_SOURCES}/gmp-$gmp_version.tar.gz | tar xf -
     cd gmp-$gmp_version
     ./configure $generic_prefix --disable-static --enable-shared
     $MAKE
    status=$?
    if [ "$status" != 0 ] ; then
       echo make of gmp failed
    else
       $MAKE install
    fi
    ) > $HOSTLOGDIR/08-pre-gmp.txt 2>&1
else
    echo not building gmp:
fi 



if test -n "$build_libtool" ; then
    echo BUILDING libtool:
    libtool_version=1.5.26
    ${WGET} http://downloads.sourceforge.net/gnuwin32/libtool-$libtool_version-bin.zip
    ${WGET} http://downloads.sourceforge.net/gnuwin32/libtool-$libtool_version-lib.zip
    (date
     cd $install_top_dir
     pwd
     7z x -y ${AUTOBUILD_SOURCES}/libtool-$libtool_version-bin.zip
     7z x -y ${AUTOBUILD_SOURCES}/libtool-$libtool_version-lib.zip
     # fix some wrong paths
     sed "s?^prefix=.*?prefix=$install_top_dir?" bin/libtoolize >libtoolize.tmp
     mv libtoolize.tmp bin/libtoolize
     sed "s?^libdir=.*?libdir=$install_top_dir/lib?" lib/libltdl.la >libltdl.tmp
     mv libltdl.tmp lib/libltdl.la     
     cd -
    ) > $HOSTLOGDIR/09-pre-libtool.txt 2>&1
else
    echo not building libtool:
fi 


if test -n "$build_readline" ; then
    echo BUILDING readline:
    readline_version=5.0-1
    ${WGET} http://downloads.sourceforge.net/gnuwin32/readline-$readline_version-bin.zip
    ${WGET} http://downloads.sourceforge.net/gnuwin32/readline-$readline_version-lib.zip
    (
    cd $install_top_dir
    date
    pwd
    7z x -y ${AUTOBUILD_SOURCES}/readline-$readline_version-bin.zip
    7z x -y ${AUTOBUILD_SOURCES}/readline-$readline_version-lib.zip
    cd -
    ) > $HOSTLOGDIR/10-pre-readline.txt 2>&1
else 
    echo not building readline:
fi 

if test -n "$build_guile" ; then 
    echo BUILDING guile:
#
guile_version=1.8.3
#guile_version=1.8.8
# not yet...
# lets try...
${WGET} http://www.mirrorservice.org/sites/ftp.gnu.org/gnu/guile/guile-${guile_version}.tar.gz
# ${WGET} http://www.ysbl.york.ac.uk/~lohkamp/software/extras/guile-${guile_version}.patch
${WGET} $win_extras_place/guile-${guile_version}.patch

cd $build_dir
( 
date
pwd
gzip -dc ${AUTOBUILD_SOURCES}/guile-${guile_version}.tar.gz | tar xf -
cd guile-${guile_version}
# we need to pass CFLAGS and LDFLAGS because there is no --with-readline-prefix# arg to guile's configure
# Werror flags is needed for gcc compiler >= 4.6
# Need a patch?
patch -p0 < ${AUTOBUILD_SOURCES}/guile-${guile_version}.patch
# make sure no pthread around?! FIXME
# dont use these flags as old compiler doesnt like it
#    CFLAGS="-I$install_top_dir/include -O -Wno-error=unused-but-set-variable -Wno-error=unused-function" \
./configure $generic_prefix \
    CFLAGS="-I$install_top_dir/include -O" \
    LDFLAGS=-L$install_top_dir/lib --with-libintl-prefix=$install_top_dir
#    --without-threads --host=i686-pc-mingw32 --disable-shared
# Multilib fix for procedures.txt
# dont think we need this
# perl -pi -e 's|threads.doc||' `find . -name Makefile`
$MAKE
status=$?
if [ "$status" != 0 ] ; then 
    echo guile make failed.
    guile_build_status=$status
else
   echo 1 ---------------------------------------------------------------------   echo '                               ' make install
   echo 1 ---------------------------------------------------------------------
   $MAKE install

   # post install windows fixes/moving of ddls (probably should make it more flexible
   # with respect to file name ending...)
   cp $install_top_dir/bin/libguile-srfi-srfi-1-v-3-3.dll $install_top_dir/bin/libguile-srfi-srfi-1-v-3.dll
   cp $install_top_dir/bin/libguile-srfi-srfi-13-14-v-3-3.dll $install_top_dir/bin/libguile-srfi-srfi-13-14-v-3.dll
   cp $install_top_dir/bin/libguile-srfi-srfi-4-v-3-3.dll $install_top_dir/bin/libguile-srfi-srfi-4-v-3.dll
   cp $install_top_dir/bin/libguile-srfi-srfi-60-v-2-2.dll $install_top_dir/bin/libguile-srfi-srfi-60-v-2.dll
   cp $install_top_dir/bin/libguilereadline-v-17-17.dll $install_top_dir/bin/libguilereadline-v-17.dll
fi 

exit $status
) > $HOSTLOGDIR/11-guile.txt 2>&1
if $status ; then 
   echo guile build failed
fi
else
    echo not building guile:
fi

# Do we need to have to set GUILE_LOAD_PATH? Maybe!!!
GUILE_LOAD_PATH=$install_top_dir/share/guile/1.8:$install_top_dir/share/guile:$install_top_dir/share/guile/site
export GUILE_LOAD_PATH
echo GUILE_LOAD_PATH is now: $GUILE_LOAD_PATH


# we wont build greg as it wont work properly anyway!!
build_greg=
if test -n "$build_greg" ; then 
    echo building greg:
    ${WGET} http://www.ysbl.york.ac.uk/~emsley/software/extras/greg-2.0.0-pe.tar.gz
    (
    date 
    gzip -dc ${AUTOBUILD_SOURCES}/greg-2.0.0-pe.tar.gz | tar xf -
    cd  greg-2.0.0-pe
    ./configure $generic_prefix
    $MAKE
    $MAKE install
    ) > $HOSTLOGDIR/11c-greg.txt 2>&1
else
    echo not building greg:
fi


if test -n "$build_guile_gtk" ; then 
    echo BUILDING guile-gtk:
#
guile_gtk_version=2.1
${WGET} http://www.mirrorservice.org/sites/ftp.gnu.org/gnu/guile-gtk/guile-gtk-$guile_gtk_version.tar.gz
#${WGET} http://www.ysbl.york.ac.uk/~lohkamp/software/extras/guile-gtk-win32.patch
${WGET} $win_extras_place/guile-gtk-win32.patch
( 
date
pwd
gzip -dc ${AUTOBUILD_SOURCES}/guile-gtk-$guile_gtk_version.tar.gz | tar xf -
cd guile-gtk-$guile_gtk_version
./configure $generic_prefix --without-gtkgl --with-glade=no --disable-static --enable-shared
# PATCH!!!!!!
patch -bp0 < ${AUTOBUILD_SOURCES}/guile-gtk-win32.patch
# now patch the libtool if needed:
# fix ulong if needed:
# sed 's/(ulong)/(unsigned long)/g' guile-gtk.c > tmp.c
# mv tmp.c guile-gtk.c
$MAKE
status=$?
guile_gtk_status=$status
if [ "$guile_gtk_status" != 0 ] ; then 
    echo Oooops guile-gtk make failed
else   
    echo 1 -------------------------------------------------------------------------
    echo '                                ' make install
    echo 1 -------------------------------------------------------------------------
    $MAKE install
fi
) > $HOSTLOGDIR/12-guile-gtk.txt 2>&1
else
    echo not building guile-gtk:
fi

if test -n "$build_guile_gui" ; then 
   echo BUILDING guile-gui:
#
guile_gui_version=0.3
#${WGET} http://www.ysbl.york.ac.uk/~emsley/software/extras/guile-gui-0.2.tar.gz
#${WGET} http://lmb.bioch.ox.ac.uk/coot/extras/guile-gui-${guile_gui_version}.tar.gz
${WGET} $extras_place/guile-gui-0.3.tar.gz
#${WGET} http://www.ysbl.york.ac.uk/~lohkamp/software/extras/guile-gui-0.2.patch
( 
date
pwd
gzip -dc ${AUTOBUILD_SOURCES}/guile-gui-${guile_gui_version}.tar.gz | tar xf -
#patch -bp0 < ${AUTOBUILD_SOURCES}/guile-gui-0.2.patch
cd guile-gui-${guile_gui_version}
./configure $generic_prefix
$MAKE
$MAKE install
) > $HOSTLOGDIR/13-guile-gui.txt 2>&1

else 
    echo not building guile-gui:
fi

echo GUILE_LOAD_PATH is now: $GUILE_LOAD_PATH

if test -n "$build_guile_lib" ; then
   echo BUILDING guile-lib:
#
guile_lib_version=0.1.6
${WGET} http://download.gna.org/guile-lib/guile-lib-$guile_lib_version.tar.gz
( 
date
pwd
gzip -dc ${AUTOBUILD_SOURCES}/guile-lib-$guile_lib_version.tar.gz | tar xf -
cd guile-lib-$guile_lib_version
# the prefix for guile-lib must be the prefix of guile, or else the sxml and 
# other library files will not be found
./configure $generic_prefix
$MAKE
$MAKE install
) > $HOSTLOGDIR/14-guile-lib.txt 2>&1
else 
    echo not building guile-lib
fi


else
   echo not building GUILE things
fi


if test -n "$build_curl" ; then 
   # we build libidn for libcurl (dont bother wiht winidn in case there are conflicts
   # dont do a separate check, if we want curl, then we get libidn
   # get libcurl from here:
   echo BUILDING libidn:
(
   libidn_version=1.15
   ${WGET} http://www.mirrorservice.org/sites/ftp.gnu.org/gnu/libidn/libidn-$libidn_version.tar.gz

   gzip -dc ${AUTOBUILD_SOURCES}/libidn-$libidn_version.tar.gz | tar xf -
   cd libidn-$libidn_version

   ./configure  $generic_prefix
   if $MAKE ; then
      $MAKE install
   fi
) > $HOSTLOGDIR/15-a-libidn.txt

   echo BUILDING curl:
(
   # get libcurl from here: 
   #libcurl_version=7.19.7
   # libcurl_version=7.27.0
   libcurl_version=7.37.0
   ${WGET} --no-check-certificate http://curl.haxx.se/download/curl-$libcurl_version.tar.gz

   gzip -dc ${AUTOBUILD_SOURCES}/curl-$libcurl_version.tar.gz | tar xf -
   cd curl-$libcurl_version
  
   # libcurl has problems with putting the libraries ine right order when we specify 
   # --with-libidn (it puts the libidn prefix libs at the end of its LDFLAGS and that 
   # is bad because /usr/lib gets in front, and /usr/lib/libidn.so is missing). So here
   # we force the libidn libs at the front of LDFLAGS.  Problem found on RHEL4-64bit 
   # (lemur).
   #
   ./configure  $generic_prefix --with-libidn=$install_top_dir LDFLAGS=-L$install_top_dir/lib
   if $MAKE ; then
      $MAKE install
   fi
) > $HOSTLOGDIR/15-b-curl.txt
else
    echo not building curl:
fi


if test -n "$build_gsl" ; then 
    echo BUILDING gsl:
#
gsl_version=1.8
# not yet
# gsl_version=1.12
# lets try 2.2.1 binaries shared for both!
gsl_version=2.2.1
#if [ -n "$shared_flag" ] ; then
#  gsl_version=1.16
#  ${WGET} http://www.mirrorservice.org/sites/ftp.gnu.org/gnu/gsl/gsl-$gsl_version.tar.gz
#else
#  ${WGET} http://downloads.sourceforge.net/gnuwin32/gsl-$gsl_version-bin.zip
#  ${WGET} http://downloads.sourceforge.net/gnuwin32/gsl-$gsl_version-lib.zip
#  ${WGET} $win_extras_place/gsl-config
#  ${WGET} $win_extras_place/gsl.m4
  ${WGETS} http://sourceforge.net/projects/gnu-scientific-library-windows/files/gsl-2.2.1_mingw-6.2.0.zip
#fi

( 
date
pwd
if [ 0 == 1 ] ; then
gzip -dc ${AUTOBUILD_SOURCES}/gsl-$gsl_version.tar.gz | tar xf -
cd gsl-$gsl_version
./configure $generic_prefix $shared_static_flag
$MAKE
status=$?
if [ "$status" != 0 ] ; then 
    echo ERROR:: GSL make failed.
    exit 2
else
   echo 1 ---------------------------------------------------------------
   echo '                                ' make install
   echo 1 ----------------------------------------------------------------
   $MAKE install
fi  
else
cd $install_top_dir
#7z x -y ${AUTOBUILD_SOURCES}/gsl-$gsl_version-bin.zip
#7z x -y ${AUTOBUILD_SOURCES}/gsl-$gsl_version-lib.zip
# gsl binaries dont have gsl-config, so we have to make our own
#cp ${AUTOBUILD_SOURCES}/gsl-config bin/
#sed "s?^prefix=.*?prefix=$install_top_dir?" bin/gsl-config >gsl-config.tmp
#mv gsl-config.tmp bin/gsl-config
# somehow need to 'remove' the dll libs as these cause access violations
# i.e. use static linking
#mv lib/libgsl.dll.a lib/libgsl.dll.a.orig
#mv lib/libgslcblas.dll.a lib/libgslcblas.dll.a.orig
#status=$?
# and there is no gsl.m4, so copy that
#cp ${AUTOBUILD_SOURCES}/gsl.m4 $install_top_dir/share/aclocal/
# END OLD
7z x -y ${AUTOBUILD_SOURCES}/gsl-2.2.1_mingw-6.2.0.zip -o${AUTOBUILD_SOURCES} gsl-2.2.1_mingw-6.2.0\\gsl-2.2.1-shared\\*
# now copy to install_top_dir
cp -r ${AUTOBUILD_SOURCES}/gsl-2.2.1_mingw-6.2.0/gsl-2.2.1-shared/* $install_top_dir/
# now adjust the path for gsl-config and *la files
sed "s?/home/Mesh/gsl_mingw/package/gsl-2.2.1-shared?$install_top_dir?" bin/gsl-config >gsl-config.tmp
mv gsl-config.tmp bin/gsl-config

sed "s?/home/Mesh/gsl_mingw/package/gsl-2.2.1-shared?$install_top_dir?" lib/libgsl.la >libgsl.la.tmp
mv libgsl.la.tmp lib/libgsl.la

sed "s?/home/Mesh/gsl_mingw/package/gsl-2.2.1-shared?$install_top_dir?" lib/libgslcblas.la >libgslcblas.la.tmp
mv libgslcblas.la.tmp lib/libgslcblas.la
if [ "$status" != 0 ] ; then 
    echo ERROR:: GSL make failed.
    exit 2
else
   echo 1 ---------------------------------------------------------------
   echo '                                ' make install
   echo 1 ----------------------------------------------------------------
fi    
fi
) > $HOSTLOGDIR/15-gsl.txt
else
    echo not building gsl:
fi

#################################################################
# Clustalw2
#################################################################
#
if test -e $install_top_dir/bin/clustalw2.exe ; then
   echo not building clustalw2
else
   ${WGET} http://www.clustal.org/download/current/clustalw-2.1-win.msi
   if [ ! -e ${AUTOBUILD_SOURCES}/clustalw-2.1.msi ] ; then
      echo failed to download clustalw2
   else
      # happy path
      (
	  mkdir clustalw-2.1
      cd clustalw-2.1/
      7z x ${AUTOBUILD_SOURCES}/clustalw-2.1.msi
      cp clustalw2.exe $install_top_dir/bin
      status=$?
      if [ $status = 0 ] ; then
          echo successfully unpacked and copied clustalw2.exe
      else
          echo install for clustalw-2.1 failed. Boo.
      fi
      ) > $HOSTLOGDIR/18-clustalw.txt 2>&1
   fi
fi

#################################################################
# Raster3D
#################################################################
#

if [ -e $install_top_dir/bin/render ] ; then
   echo not building Raster3D render
else

   raster3d_version=3.0-3
   # raster3d depends on libgd to make png images
   ${WGET} http://skuld.bmsc.washington.edu/raster3d/Raster3D_$raster3d_version.tar.gz
   # not needed for render itself but lets build all
   ${WGET} $win_extras_place/raster3d_win64.patch

   if [ ! -e ${AUTOBUILD_SOURCES}/Raster3D_$raster3d_version.tar.gz ] ; then

      echo missing Raster3D tar file

   else
      # need and get libgd from system
      echo build render...............
      ( 
       date
       pwd
       # build render
       #
       if [ ! -e $install_top_dir/bin/render ] ; then 
          # now build it.
          gzip -dc ${AUTOBUILD_SOURCES}/Raster3D_$raster3d_version.tar.gz | tar xf -
          cd Raster3D_$raster3d_version
		  patch -p0 < ${AUTOBUILD_SOURCES}/raster3d_win64.patch

          make win64 # FIXME for Darwin

          echo about to do this: $MAKE
          $MAKE
          ls -l render

		  status = $?

          if $status ; then 
  	         make prefix=$install_top_dir install
	         # did that work?  I doubt it. Let's do it by hand
             if [ ! -e $install_top_dir/bin/render ] ; then
  	            echo Hand copy: cp render $install_top_dir/bin/
  	            cp render $install_top_dir/bin/
             fi
          else
             echo no render built in `pwd`
          fi
          cd -
       else 
          echo $install_top_dir/bin/render already exists, no build
       fi
       ) > $HOSTLOGDIR/15-raster3d.txt 2>&1
   fi
fi


#######################
#### build glob
######################
if test -n "$build_glob" ; then
  echo BUILDING glob:
  ${WGET} $win_extras_place/glob-1.0.tar.bz2
  (
   date
   pwd
   bzip2 -cd ${AUTOBULD_SOURCES}/glob-1.0.tar.bz2 | tar xf -
   cd glob-1.0
   ./configure $generic_prefix
   make
   cp glob.h $install_top_dir/include
   cp libglob.a $install_top_dir/lib
   if [ $build_shared = 1 ] ; then
     g++ -shared -o libglob.dll glob.o fnmatch.o -Wl,--out-implib,libglob.dll.a
     cp libglob.dll $install_top_dir/bin
     cp libglob.dll.a $install_top_dir/lib
   fi
   cd -
  ) > $HOSTLOGDIR/23-glob.log
else
  echo not building glob
fi

###############################################################################
##########         get Coot                                       #############
###############################################################################
#
echo BUILDING coot: version $coot_version, python=$ENABLE_PYTHON_COOT guile=$ENABLE_GUILE_COOT
wincoot_version=${coot_version/coot-}
if [ "$build_coot_prerelease" != 1 ] ; then 
   # normal release coot
   ${WGET} $release_server_dir/$coot_version.tar.gz
   if [ ! $? = 0 ] ; then
      echo failed to wget $release_server_dir/$coot_version.tar.gz   
      my_exit 2 wget-fail-coot-source
   fi
   # ${WGET} http://www.ysbl.york.ac.uk/~emsley/software/coot-static.patch
else 
   # If we are building pre-release coot_source_tar_file is set only if we can find 
   # a pre-release source tar in the pre-release directory, otherwise it is not set
   if [ -n "$coot_source_tar_file" ] ; then 
      ${WGET} $coot_source_tar_file
      if [ ! $? = 0 ] ; then
         echo failed to wget $coot_source_tar_file
         my_exit 2 wget-fail-coot-source
      fi 
   else 
      # compile release code then:
      ${WGET} $release_server_dir/$coot_version.tar.gz
      if [ ! $? = 0 ] ; then
         echo failed to wget $release_server_dir/$coot_version.tar.gz
         my_exit 2 wget-fail-coot-source
      fi
   fi 
   coot_revision=`echo $coot_version | awk '{a=$1; i=index(a,"revision"); print substr(a,i)}'`
   echo coot_version set to $coot_version
   echo coot_revision set to $coot_revision
   # ${WGET} http://www.ysbl.york.ac.uk/~emsley/software/coot-static.patch
fi

# we shall get the syminfo.lib for windows too
# not needed any more
#${WGET} http://www.ysbl.york.ac.uk/~lohkamp/software/extras/syminfo_win.lib

echo using coot version $coot_version
ls -ls ${AUTOBUILD_SOURCES}/$coot_version.tar.gz
if [ -e ${AUTOBUILD_SOURCES}/$coot_version.tar.gz ] ; then
   echo good ${AUTOBUILD_SOURCES}/$coot_version.tar.gz exists
else 
   echo badness ${AUTOBUILD_SOURCES}/$coot_version.tar.gz does not exist.
   echo nothing left to do then.  Goodbye.
   my_exit 2 $coot_version.tar.gz not found
fi
# we have to go to build dir
cd $build_dir
date
pwd
gzip -dc ${AUTOBUILD_SOURCES}/$coot_version.tar.gz | tar xf -
coot_dir_name=`echo $coot_version | sed 's/-revision.*//'`
cd $coot_dir_name

# now that we are in coot build dir we overwrite syminfo.lib with the windows
# one
# Change: replace it with internal one. Cant have 'wrong' one in root dir
echo replacing syminfo.lib with windows version
mv syminfo.lib syminfo.lib.orig
cp windows/syminfo.lib syminfo.lib
# get windows cootrc
#wget -N -P ${HOME}/autobuild/extras http://www.ysbl.york.ac.uk/~lohkamp/software/extras/cootrc
wget -N -P ${HOME}/autobuild/extras $win_extras_place/cootrc

if test -n "$glib_installed" ; then
    coot_extra_args="$coot_extra_args --with-glib-prefix=$install_top_dir"
fi
if test -n "$gtk_installed" ; then
    coot_extra_args="$coot_extra_args --with-gtk-prefix=$install_top_dir"
fi

if [ "$ENABLE_GUILE_COOT" = "yes" ] ; then
    guile_scripting="--with-guile --with-guile-gtk --with-guile-gtk-prefix=$install_top_dir"
fi

# if ENABLE_PYTHON_COOT is not set, then we choose a day of the week
# to build a python version.

# if ENABLE_PYTHON_COOT is set, then if it is set to 0 or no then we
# do not build a python version, otherwise we do build a python
# version

if [ -n "$ENABLE_PYTHON_COOT" ] ; then 
    # it was set to something
    if [ "$ENABLE_PYTHON_COOT" != "0" ] ; then 
       if [ "$ENABLE_PYTHON_COOT" != "no" ] ; then 
          python_scripting='--with-python --with-pygtk'
       fi
    fi
else 
    # if ENABLE_PYTHON_COOT was not set, then turn on python scripting
    python_scripting='--with-python --with-pygtk'
fi

# no longer makes sense now that python is in by default
# else 
#    time_date=`date`
#    if [ ${time_date:0:3} = "Sun" ] ; then
#       scripting='--with-python'
#    fi
#    if [ ${time_date:0:3} = "Sun" ] ; then
#       scripting='--with-python'
#   fi
# fi




###############################################################################
##########         build Coot                                     #############
###############################################################################
#
echo BUILDING coot: version $coot_version, python=$ENABLE_PYTHON_COOT guile=$ENABLE_GUILE_COOT

# set the python tag outside the compile/install sub-shell.
if [ "$ENABLE_PYTHON_COOT" = "no" ] ; then 
   python_tag=
else 
   python_tag=-python
fi
(
date

#if [ "$ENABLE_PYTHON_COOT" = "no" ] ; then 
#   echo INFO:: not a pythonized build
#   cp src/blank.cc src/coot_wrap_python_gkt1.cc
#   cp src/blank.cc src/coot_wrap_python_gkt2.cc
#   # only gtk2 on windows
#   cp src/blank.cc src/coot_wrap_guile_gtk1.cc
#else 
#   echo INFO:: A pythonized build
#fi

#if [ "$ENABLE_GUILE_COOT" = "no" ] ; then 
#   echo INFO:: not a guilized build
#   cp src/blank.cc src/coot_wrap_guile_gtk1.cc
#   cp src/blank.cc src/coot_wrap_guile_gtk2.cc
#   # only gtk2 on windows
#   cp src/blank.cc src/coot_wrap_python_gkt1.cc
#else 
#   echo INFO:: A guilized build
#fi
#
#      CXXFLAGS="-g -O"
# consider getting rid of $shared_static_flag, which does a --disable-shared.
# i.e. we should keep and use shared libs
#
# dont use -static-libgcc on windows otherwise we cannot throw exceptions.
# means we need to supply libgcc_s_dw2-1.dll
if [ $build_shared = 1 ]  ; then
  export CXXFLAGS="-g -O"
else
  export CXXFLAGS="-g -O -static-libstdc++"
fi

# for boost and rdkit:
if [ $build_enhanced_ligand = 1 ]  ; then
    coot_extra_args+=" --with-enhanced-ligand-tools  --with-boost=${install_top_dir} --with-boost-python=yes"
    # I think we have to export this otherwise there is some configure issue
    export RDKIT_CXXFLAGS="-I${install_top_dir}/include/rdkit"
    export RDKIT_LIBS="-L${install_top_dir}/lib -lRDKitDescriptors -lRDKitSubgraphs -lRDKitPartialCharges -lRDKitForceFieldHelpers -lRDKitForceField -lRDKitMolChemicalFeatures -lRDKitSubstructMatch -lRDKitOptimizer -lRDKitDepictor -lRDKitFileParsers -lRDKitRDGeometryLib -lRDKitGraphMol -lRDKitSmilesParse -lRDKitDistGeomHelpers -lRDKitDataStructs -lRDKitRDGeneral"
fi

if [ $architecture = x86_64 ] ; then 
   # This could well be too general a test, certainly on 64 bit CentOS 5 we need this, 
   # and possibly on 64 bit Gutsy.

   # There is a problem quoting this, e.g.
   # coot_optim_args="CXXFLAGS='\"-g -O\"'" fails in configure
   #coot_optim_args="CXXFLAGS=-gO"
   #coot_optim_args="CXXFLAGS=\"-g -O\""
   export CXXFLAGS="-g -O"
fi

# This is not working, need a better way (if any)
# cbis_n=$(cmd /c "net user $USERNAME | FIND 'Full Name'")
cbis_n=
if [ -z $cbis_n ] ; then
  cbis_n=$USERNAME
fi
cbis_d=$(date +'%a %d %b %H%M.%S %Z %Y')
coot_build_info_string="built by: $cbis_n build-host: $HOST on: $cbis_d"

# this is a quick fix, and should be done properly at some point
coot_optim_args="-build=i686-pc-mingw32 --with-glob-prefix=${install_top_dir}"

# should rm libtool to make sure we use OS one
if [ -e libtool ] ; then
  echo rm libtool for clean build
  rm libtool
fi

# quick hack for large maps
export LDFLAGS="-Wl,--large-address-aware"

echo From tar file: ${AUTOBUILD_SOURCES}/$coot_version.tar.gz
echo building in: $PWD
echo ./configure $coot_prefix \
    --with-fftw-prefix=$install_top_dir \
    $goocanvas_args     \
    $glut_prefix        \
    COOT_BUILD_INFO_STRING="$coot_build_info_string" \
    $guile_scripting          \
    $python_scripting   \
    $shared_static_flag \
    $coot_optim_args	  \
    $coot_extra_args

./configure $coot_prefix \
    --with-fftw-prefix=$install_top_dir \
    $goocanvas_args     \
    $glut_prefix        \
    COOT_BUILD_INFO_STRING="$coot_build_info_string" \
    $guile_scripting          \
    $python_scripting   \
    $shared_static_flag \
    $coot_optim_args	  \
    $coot_extra_args

# consider adding -DCOOT_SYS_TYPE=systype (or something like that)
# here, so that coot --version-info/full returns it.

if [ $update_libtool = 1 ] ; then
   echo need to update libtool here $PWD
   cp $install_top_dir/bin/libtool .
else 
   echo NO need to update libtool $PWD
fi

#rm src/coot_wrap_guile_pre_gtk2.cc
#rm src/coot_wrap_python_pre_gtk2.cc

# make a clean version?!
if [ "$make_clean_coot" = "yes" ] ; then
    $MAKE clean
    echo make clean
fi

#$MAKE
MAKE=$MAKE" -r"
$MAKE

status=$?
if [ "$status" != 0 ] ; then 
    echo make failed.
    bad_coot_make=1
    exit 2
else
   echo 1 ---------------------------------------------------------------
   echo '                                ' make install
   echo 1 ----------------------------------------------------------------
   $MAKE install-strip
   # BL says/asks:: is this necessary? Shouldnt coot.py be copied in install
   # anyway? And its the wrong place now!? remove!
   #if [ "$python_scripting" = '--with-python' ] ; then
   #   echo copying src/coot.py $install_top_dir/share/coot/python
   #   cp src/coot.py $install_top_dir/share/coot/python
   #fi
fi
) > $HOSTLOGDIR/16-coot.txt 2>&1

#         --with-gsl-prefix=$install_top_dir \
#        --with-glib-prefix=$install_top_dir \
#         --with-gtk-prefix=$install_top_dir \
#       --with-gtkgl-prefix=$install_top_dir \

coot_build_status=$?
if [ $coot_build_status != 0 ] ; then
    echo coot build failed, exiting.
    echo fail-build $coot_revision > $LOGS/gtk2${build_type}-build-status
    my_exit 2 $coot_revision
else 
    # and finally write a coot-version file for the installer
    echo '!define WinCootVersion "'${wincoot_version}'"' >$install_top_dir/coot-version

    echo coot build was good.
    echo pass-build $coot_revision > $LOGS/gtk2${build_type}-build-status
fi
echo done coot build. 


# now, do we need to add the extra data files, the refmac monomer
# library and the reference structures?

# 8/5/11 change to Garib's new dicionary.
#refmac_mon_lib=refmac-monomer-library-20090929.tar.gz
# mon_lib_dir=http://www.ysbl.york.ac.uk/~garib/refmac/data/refmac_experimental
# mon_lib_dir=http://www2.mrc-lmb.cam.ac.uk/groups/murshudov/content/refmac/Dictionary
#refmac_mon_lib=refmac_dictionary_v5.41.tar.gz

# new style
mon_lib_dir=http://www2.mrc-lmb.cam.ac.uk/personal/pemsley/coot/dependencies
refmac_mon_lib=refmac-monomer-library.tar.gz

if [ -e $install_top_dir/share/coot/lib/data/monomers ] ; then
    echo INFO:: installation has refmac monomer library
else 
    echo INSTALLING refmac monomer library...
    $WGET $mon_lib_dir/$refmac_mon_lib
    mkdir -p $install_top_dir/share/coot/lib/data
    tar xzCf $install_top_dir/share/coot/lib/data $AUTOBUILD_SOURCES/$refmac_mon_lib
fi 
if [ -e $install_top_dir/share/coot/reference-structures ] ; then
    echo INFO:: installation has reference structures
else 
    echo GETTING reference structures tar...
    echo GETTING reference structures tar... &>2
    ${WGET} $extras_place/reference-structures.tar.gz
    if [ -e $AUTOBUILD_SOURCES/reference-structures.tar.gz ] ; then
       echo INSTALLING reference structures...
       tar xzCf $install_top_dir/share/coot $AUTOBUILD_SOURCES/reference-structures.tar.gz
    else 
       echo FAIL wget for reference-structures.tar.gz failed.
    fi
fi

# clear up the library dependencies
# not needed on windows as I fix this with the installer...

#clear_up_type=
#if [ $shared_static_flag != "--disable-static" ] ; then
#    clear_up_type=clear-static
#fi   
#if [ $shared_static_flag != "--disable-shared" ] ; then
#    clear_up_type=clear-dynamic
#fi   
#
#if [ $clear_up_type != "" ] ; then 
#   slim_dir=`dirname $install_top_dir`/coot-${OS}-${systype}-gtk2
#   post_install_slim $install_top_dir $slim_dir $clear_up_type 
#fi

# clean up old test status:
if [ -e $LOGS/gtk2${build_type}-test-status ] ; then
   rm $LOGS/gtk2${build_type}-test-status
fi
# clean up old test logs (needed?!):
if [ -e $LOGS/gtk2${build_type}-test-status.log ] ; then
   rm $LOGS/gtk2${build_type}-test-status.log
fi
# run tests
echo running tests...

if test "$run_tests" = true ; then
   # download the test data to make sure we have the latest version.
   echo downloading test data...
   ${WGET} http://www2.mrc-lmb.cam.ac.uk/Personal/pemsley/coot/data/greg-data.tar.gz
   echo "   done."
   cd ~/data
   gzip -cd ${AUTOBUILD_SOURCES}/greg-data.tar.gz | tar xf - 
   cd -
fi

test_coot_python > $LOGS/gtk2${build_type}-test.log 2>&1
coot_test_status=$?
gtk2=-gtk2
if [ $coot_test_status = 0 ] ; then
   echo ========================
   echo '   ' coot test passed
   echo ========----============
   echo pass-test > $LOGS/gtk2${build_type}-test-status
   # no need for this! The installer and script around will take care of this
   #if test "$do_nightlies" = "1" ; then 
   #   if [ -d $BINARY_TAR_DEST_DIR ] ; then 

         # original full fat:
         # make_tar `basename $install_top_dir` $BINARY_TAR_DEST_DIR/${coot_version}-binary-full-${OS}-${systype}${python_tag}.tar.gz
         # slimmed:
#	 make_tar `basename $slim_dir` $BINARY_TAR_DEST_DIR/${coot_version}-binary-${OS}-${systype}${python_tag}${gtk2}.tar.gz

         # update the ChangeLog, README and RELEASE-NOTES
#         cd "$build_dir"
#         cd $coot_dir_name
#         cp ChangeLog $BINARY_TAR_DEST_DIR
#         cp README    $BINARY_TAR_DEST_DIR/coot-README
#         cp RELEASE-NOTES    $BINARY_TAR_DEST_DIR/${coot_version}-RELEASE-NOTES
#      else 
#         echo directory for binaries does not exist. Skipping tar.
#      fi
#   else
#      echo not doing tar files for nightlies: $do_nightlies
#   fi
else
   echo ========================
   echo '  ' coot test failed
   echo ========================
   echo fail-test $coot_revision > $LOGS/gtk2${build_type}-test-status
fi

# now copy the log files
cp -r ${LOGS} ${PUBLIC_HTML_LOGS}
echo copy the log files from ${LOGS} to ${PUBLIC_HTML_LOGS}
# we have to make sure they are readable!
# either change once manually or
# run in masta unix script

# we set the binary type here and pass it to the installer script
# only if that works it shoudl be copied and updated on the website. 
binary_type_latest=type-binary-${OS}-${systype}${python_tag}${gtk2}-latest.txt


# we write a number of variables to a file which we import in the
# masta script so that we preserve these
# first remove an the old file
var_file=${HOME}/wincoot-installer-variables
echo deleting $var_file
rm -f $var_file
echo LOGS=${LOGS}                          > $var_file
echo NIGHTLY_DEST_DIR=${NIGHTLY_DEST_DIR}   >> $var_file
echo wincoot_version=$wincoot_version       >> $var_file
echo build_coot_prerelease=$build_coot_prerelease >> $var_file
echo coot_build_status=$coot_build_status   >> $var_file
echo coot_test_status=$coot_test_status     >> $var_file
echo binary_type_latest=$binary_type_latest >> $var_file
echo HOSTLOG_STUB=$compilers_dir${build_type} >> $var_file

echo finished.
