#!/bin/bash
# This is the master script to make a windows Coot installer
#
# args: pre-release guile installer_only
#
# 1.) build a python version
# 2.) build a python + guile version
# 3.) pack into an installer
#
# can take build_coot_prerelease arg to manually build stable release e.g.
# is command line arg here... damn msys shell
#
# set this to "no" if you don't want to compile the pre-release code.
# build_coot_prerelease=
build_coot_prerelease=${1:-1}
if [ -e /z/make_stable_build ] ; then
  build_coot_prerelease=0
  if [ -e /z/make_clean_wincoot_stable ] ; then
     extra_flag="veryclean"
     rm /z/make_clean_wincoot_stable
  fi
fi
if [ -z "$build_coot_prerelease" ] ; then
  build_coot_prerelease=0
fi

if [ "$build_coot_prerelease" -ne "0" ] ; then 
  if [ -e /z/make_clean_wincoot_prerelease ] ; then
     extra_flag="veryclean"
     rm /z/make_clean_wincoot_prerelease
  fi
fi

# option to not build guile
# BL note:: this needs to become more flexible!!!
# fix make installer logic, rather check that ok 
make_guile=${2:-0}
if [ -e /z/make_guile ] ; then
  make_guile=1
fi
if [ -z "$make_guile" ] ; then
  make_guile=1
fi

# BL note:: this needs to become more flexible!!!
make_installer_only=${3:-0}
if [ -e /z/make_installer_only ] ; then
  make_installer_only=1
fi
if [ -z "$make_installer_only" ] ; then
  make_installer_only=1
fi

# BL note:: this needs to become more flexible!!!
build_enhanced_ligand=${4:-1}
if [ -e /z/make_no_EL ] ; then
  build_enhanced_ligand=0
fi
if [ -z "$build_enhanced_ligand" ] ; then
  build_enhanced_ligand=1
fi

#
BINARY_DIR=/c/msys64/home/bernhard/public_html/software/binaries/pre-release
PRE_BINARY_DIR=/c/msys64/home/bernhard/public_html/software/binaries/pre-release
# test if there is enough disk space first
(
fsutil.exe volume diskfree c: > ${HOME}/diskspace.tmp
free_line=`grep 'avail' ${HOME}/diskspace.tmp`
free_space=${free_line:30}
set -- ${free_space}
if [[ $1 -gt 500000000 ]] ; then
   echo enough disk space $free_space, continue
else
   echo delete windows files with cleanmgr
   # note: not compressing old files!!
   cleanmgr /sagerun:69
   echo not enough disk space left, run clean up script first
   sh ${HOME}/remove_binaries.sh $PRE_BINARY_DIR
fi
rm ${HOME}/diskspace.tmp
) 2>&1 > $HOME/disk-space-status
OS=`uname`
OS=${OS%-*}
HOST=`hostname`
HOST=${HOST%-*}

# function to copy all logs to windos host
# not copying status files yet. FIXME
function copy_logs {
  cp -p disk-space-status /z/build-logs/${OS}-${HOST}/disk-space-status

  echo Copy logs from LOCAL to PUBLIC $1
  echo Copy logs from LOCAL $LOCAL_HTML_LOGS to PUBLIC $PUBLIC_HTML_LOGS
  if [ $1 = "python" ] ; then 
      # copy log files from local to public html
      cp -p $LOCAL_HTML_LOGS/gtk2-build.log $PUBLIC_HTML_LOGS/
      cp -p $LOCAL_HTML_LOGS/gtk2-build.log $PUBLIC_HTML_LOGS/gtk2-python-build.log
      cp -a $LOCAL_HTML_LOGS/$HOSTLOG_STUB  $PUBLIC_HTML_LOGS/
      cp -p $LOCAL_HTML_LOGS/gtk2-test.log  $PUBLIC_HTML_LOGS/
      cp -p $LOCAL_HTML_LOGS/gtk2-test.log  $PUBLIC_HTML_LOGS/gtk2-python-test.log
  else
    # copy log files from local to public html
    if [ $make_guile != 0 ] ; then 
      cp -p $LOCAL_HTML_LOGS/gtk2-guile-build.log $PUBLIC_HTML_LOGS/
      cp -a $LOCAL_HTML_LOGS/${HOSTLOG_STUB}-guile/.  $PUBLIC_HTML_LOGS/
      cp -p $LOCAL_HTML_LOGS/gtk2-guile-test.log  $PUBLIC_HTML_LOGS/
    fi
  fi

}

# location of the build-it script
build_it=${HOME}/Projects/coot-gtk4/build-it-win

# location of makensis.exe
makensis="/c/Program Files (x86)/NSIS/makensis.exe"

# location of installerscript
wincoot_installer_script=${HOME}/Projects/coot-gtk4/windows/WinCoot_install_masta.nsi

# coot_version file for python and guile+python build
LOCAL_HTML_LOGS=$HOME/public_html/build-logs/${OS}-${HOST}
PUBLIC_HTML_LOGS=/z/build-logs/${OS}-${HOST}
PUBLIC_STABLE_DEST_DIR=${PUBLIC_STABLE_DEST_DIR:=/z/software/binaries/stable}
PUBLIC_NIGHTLY_DEST_DIR=${PUBLIC_NIGHTLY_DEST_DIR:=/z/software/binaries/pre-release}

# before we start building, lets update the test data files
#cp -ur /h/data/greg-data/* ~/data/greg-data
# not any more, dealt with in build-it-win

# before we really start building, lets do a git pull from BL repo to get the
# latest build script
cd ~/Projects/coot-gtk4
git pull 
cd -

# we build both, python and guile+python, coot versions until we have 
# the same coot version for both
# give up after 3 tries
coot_version_status=1
coot_test_status=1
build_cycle=0
minor_build_cycle=0
build_installer=0
(

if [ $build_coot_prerelease == 0 ] ; then 
  echo building stable installer
else
  echo building pre-release installer
fi

if [ $make_guile == 0 ] ; then 
  echo building without guile
else
  echo building with guile
fi

if [ $make_installer_only == 1 ] ; then
  echo Only packing installer now
else
  echo building and making installer
fi

if [ "$build_coot_prerelease" = "0" ] ; then
    install_top_dir=${HOME}/autobuild/${OS}-${HOST}-gtk4
else
    install_top_dir=${HOME}/autobuild/${OS}-${HOST}-pre-release-gtk4
fi

# another checkpoint to remove debug symbols
strip $install_top_dir/bin/coot-bin.exe

if [ $make_installer_only == 0 ] ; then

    while [ $coot_version_status != 0 ]
      do
      # build a python version
      echo writing progress status to public html $PUBLIC_HTML_LOGS
      echo write to file build-in-progress @`date +"%a_%d_%b_%H:%M"`
      echo build-in-progress @`date +"%a_%d_%b_%H:%M"`> $PUBLIC_HTML_LOGS/gtk2-build-status
      echo waiting for build       > $PUBLIC_HTML_LOGS/gtk2-test-status
      echo BUILDING:: python WinCoot

      # do the build
      echo Now build with:: run_tests=true build_coot_prerelease=${build_coot_prerelease} build_enhanced_ligand=$build_enhanced_ligand $build_it $extra_flag
      run_tests=true build_coot_prerelease=${build_coot_prerelease} build_enhanced_ligand=$build_enhanced_ligand $build_it $extra_flag
      python_build_status=$?
      echo "python build (and test) status: " $python_build_status
      copy_logs python
      # read in variables from install run
      . ${HOME}/wincoot-installer-variables
      # NOTE:: this overrides what is given in commandline args. Shouldnt. FIXME
      if [ -z "$build_coot_prerelease" ] ; then
          build_coot_prerelease=0
      fi
      if [ -z "$coot_test_status" ] ; then
          coot_test_status=1
      fi
      # copy to public place too
      cp ${HOME}/wincoot-installer-variables $PUBLIC_HTML_LOGS/

      # if failed dont bother with a guile build and other settings
      if [ "$coot_build_status" = "0" ] ; then

          COOT_PYTHON_VERSION=$install_top_dir/coot-version
          if [ $make_guile != 0 ] ; then 
              COOT_GUILE_VERSION=$install_top_dir-guile/coot-version
              diff ${COOT_PYTHON_VERSION} ${COOT_GUILE_VERSION} 
              coot_version_status=$?
          else
              coot_version_status=0
          fi

          if [ "$build_coot_prerelease" = "0" ] ; then
          # stable release
              touch /z/make_clean_wincoot_prerelease
          else
          # pre-release
              touch /z/make_clean_wincoot_stable
          fi

          if [ $make_guile != 0 ] ; then 
              echo 'waiting for guile build      ' > $PUBLIC_HTML_LOGS/gtk2-test-status
              echo BUILDING:: python+guile WinCoot
              # possibly could simplify extra flag, but issue if bails out on guile build
              extra_flag=
              if [ "$minor_build_cycle" = "2" ] ; then
                  extra_flag="clean"
              fi
              if [ "$build_coot_prerelease" = "0" ] ; then
              # stable release
                  if [ -e /z/make_clean_wincoot_stable-guile ] ; then
                      extra_flag="veryclean"
                      rm /z/make_clean_wincoot_stable-guile
                  fi
              else
              # pre-release
                  if [ -e /z/make_clean_wincoot_prerelease-guile ] ; then
                      extra_flag="veryclean"
                      rm /z/make_clean_wincoot_prerelease-guile
                  fi
              fi
              echo Now build with:: run_tests=true build_coot_prerelease=${build_coot_prerelease} $build_it guile $extra_flag
              run_tests=true build_coot_prerelease=${build_coot_prerelease} $build_it guile $extra_flag

              copy_logs guile
              diff ${COOT_PYTHON_VERSION} ${COOT_GUILE_VERSION} 
              coot_version_status=$?

              if [ "$build_coot_prerelease" = "0" ] ; then
                  # stable release
                  touch /z/make_clean_wincoot_prerelease-guile
              else
                  # pre-release
                  touch /z/make_clean_wincoot_stable-guile
              fi

              if [ "$coot_version_status" = "1" ] ; then
                  echo 'python and python+guile build differ => build again'
                  build_cycle=$(($build_cycle+1))
                  echo tried $build_cycle times so far
                  if [ "$build_cycle" = "3" ] ; then
                      echo We tried 3 times to build consistent python and python+guile version
                      echo BUT FAILED!!
                      echo exiting build!
                      build_installer=1
                      coot_version_status=0
                  fi
              fi
          fi 
          # end make_guile block
      else
          # Coot build was bad

          # coot python did not build ok! We try 3 more times
          echo python build failed '=>' try again
          minor_build_cycle=$(($minor_build_cycle+1))
          echo tried $minor_build_cycle times so far

          # make a clean build of failed 3 times previously (last resort)
          # shall we reset the counter? not yet
          extra_flag=
          if [ "$minor_build_cycle" = "2" ] ; then
              extra_flag="clean"
          fi
          if [ "$build_coot_prerelease" = "0" ] ; then
              # stable release
              if [ -e /z/make_clean_wincoot_stable ] ; then
                  extra_flag="veryclean"
                  rm /z/make_clean_wincoot_stable
              fi
          else
              # pre-release
              if [ -e /z/make_clean_wincoot_prerelease ] ; then
                  extra_flag="veryclean"
                  rm /z/make_clean_wincoot_prerelease
              fi
          fi

          if [ "$minor_build_cycle" = "3" ] ; then
              echo We tried 3 times to build python coot
              echo BUT FAILED!!
              echo exiting build!
              build_installer=1
              coot_version_status=0
          fi
      fi
    done
else
 # this is for installer only
    rm /z/make_installer_only
    . ${HOME}/wincoot-installer-variables
    coot_test_status=0
    echo '!define WinCootVersion "'${wincoot_version}'"' >$install_top_dir/coot-version
    echo '!define cif_dict_filename "monomers_050924.tar.gz"' >>$install_top_dir/coot-version
fi

# flag for makensis, i.e. overwrite binary dir when stable release
makensis_flag=
top_dir=//Dtop_dir="$install_top_dir"
abs_home=`cygpath -aw $HOME`
src_dir=//Dsrc_dir="$abs_home\Projects\coot-gtk4"
echo srcdir is $src_dir
PUBLIC_BINARY_DIR=$PUBLIC_NIGHTLY_DEST_DIR
if [ "$build_coot_prerelease" != "1" ] ; then
   # stable release
   echo Have stable release and set variables now
   makensis_flag=//Dbinary_dir="C:\msys64\home\bernhard\public_html\software\binaries\stable"
   BINARY_DIR=/c/msys64/home/bernhard/public_html/software/binaries/stable
   PUBLIC_BINARY_DIR=$PUBLIC_STABLE_DEST_DIR
fi

# wincoot installer exe filename
wincoot_exe=WinCoot-${wincoot_version}.exe
echo wincoot_exe is $wincoot_exe 
wincoot_exe_pub=${PUBLIC_BINARY_DIR}/${wincoot_exe}

# test if we already have this version, otherwise we dont need to make 
# an installer again
if test -e ${wincoot_exe_pub} ; then
   build_installer=999
fi

# now see if the tests passed
if [ "$coot_test_status" = "1" ] ; then 
   # we have failed python test, dont build installer
   cp $LOCAL_HTML_LOGS/gtk2-test-status $PUBLIC_HTML_LOGS/gtk2-test-status
   build_installer=1
   echo python test failed, so not building installer
else
   # passed python test, but passed guile&python test?
 if [ $make_guile != 0 ] ; then 
   cp $LOCAL_HTML_LOGS/gtk2-test-status $PUBLIC_HTML_LOGS/gtk2-test-status
   diff ${PUBLIC_HTML_LOGS}/gtk2-test-status ${PUBLIC_HTML_LOGS}/gtk2-guile-test-status 
   test_diff=$?
   if [ "$test_diff" = "1" ] ; then
      # test results differ, i.e. guile&python build test failed
      # dont build installer
      echo fail-test       > $PUBLIC_HTML_LOGS/gtk2-test-status
      echo 'python test on python&guile build failed, so not building installer'
      build_installer=1
   fi
 fi
fi

# run the installer
if [ "$build_installer" = "0" ] ; then
   # download the latest documentation first
   # FIXME :: is old replace with one with mouse!!
   #wget -N -P ${HOME}/autobuild/extras http://www.ysbl.york.ac.uk/~emsley/coot/coot-keys-and-buttons.pdf
   wget -N -P ${HOME}/autobuild/extras http://www2.mrc-lmb.cam.ac.uk/personal/pemsley/coot/web/docs/coot-user-manual.pdf
   wget -N -P ${HOME}/autobuild/extras http://www2.mrc-lmb.cam.ac.uk/personal/pemsley/coot/web/docs/crib-sheet.pdf
   wget -N -P ${HOME}/autobuild/extras http://www2.mrc-lmb.cam.ac.uk/personal/pemsley/coot/web/tutorial/tutorial.pdf
   wget -N -P ${HOME}/autobuild/extras http://www2.mrc-lmb.cam.ac.uk/personal/pemsley/coot/web/tutorial/tutorial-2.pdf
   # and download the bat run files
   # actually these come from the git repository now
#   wget -N -P ${HOME}/autobuild/extras http://www.ysbl.york.ac.uk/~lohkamp/software/extras/runwincoot.bat
#   wget -N -P ${HOME}/autobuild/extras http://www.ysbl.york.ac.uk/~lohkamp/software/extras/runwincoot_ccp4.bat
#   wget -N -P ${HOME}/autobuild/extras http://www.ysbl.york.ac.uk/~lohkamp/software/extras/runwincoot_ccp4_vista.bat
   # But should get the icons e.g.
   wget -N -P ${HOME}/autobuild/extras http://bernhardcl.github.io/coot/software/extras/coot-icon.ico
   wget -N -P ${HOME}/autobuild/extras http://bernhardcl.github.io/coot/software/extras/rama_all.ico
   wget -N -P ${HOME}/autobuild/extras http://bernhardcl.github.io/coot/software/extras/go-to-ligand.ico
   # some more extras (for probe and reduce)
   wget --no-check-certificate -N -P ${HOME}/autobuild/extras https://github.com/bernhardcl/coot/raw/gh-binaries/auxil_binaries/libgcc_s_dw2-1.dll
   wget --no-check-certificate -N -P ${HOME}/autobuild/extras https://github.com/bernhardcl/coot/raw/gh-binaries/auxil_binaries/libstdc++-6.dll
   # get probe and reduce (compiled self)
   wget --no-check-certificate -N -P ${HOME}/autobuild/extras https://github.com/bernhardcl/coot/raw/gh-binaries/auxil_binaries/probe.exe
   wget --no-check-certificate -N -P ${HOME}/autobuild/extras https://github.com/bernhardcl/coot/raw/gh-binaries/auxil_binaries/reduce.exe
   wget -N -P ${HOME}/autobuild/extras http://bernhardcl.github.io/coot/software/extras/reduce_wwPDB_het_dict.txt
   wget -N -P ${HOME}/autobuild/extras http://bernhardcl.github.io/coot/software/extras/probe_reduce.txt
   # some more...
   wget --no-check-certificate -N -P ${HOME}/autobuild/extras https://github.com/bernhardcl/coot/raw/gh-binaries/auxil_binaries/ppm2bmp.exe
   wget --no-check-certificate -N -P ${HOME}/autobuild/extras https://github.com/bernhardcl/coot/raw/gh-binaries/auxil_binaries/gzip.exe

   # now make the installer
   echo installer-progress > $PUBLIC_HTML_LOGS/gtk2-build-status
   echo
   echo making WinCoot installer
   echo in dir `pwd` with command:
   echo $makensis //V4 ${makensis_flag} ${src_dir} $wincoot_installer_script
   echo
   "$makensis" //V4 ${makensis_flag} ${src_dir} $wincoot_installer_script
   nsis_status=$?
   if [ "$nsis_status" = "0" ] ; then
       if [ -e /z/make_stable_build ] ; then
          # clean up since we managed
           rm /z/make_stable_build
       fi
	# move files in correct places
	# or do it before?!?
       echo Installer script run successful!!
       echo make md5sum from ${BINARY_DIR}/${wincoot_exe} to ${BINARY_DIR}/${wincoot_exe}.md5sum
       md5sum ${BINARY_DIR}/${wincoot_exe} > ${BINARY_DIR}/${wincoot_exe}.md5sum
       /bin/ls -l ${BINARY_DIR}/${wincoot_exe}>> ${BINARY_DIR}/${wincoot_exe}.md5sum
       # now update the binary_type_latest stuff 
       echo write wincoot_version WinCoot-${wincoot_version} to file ${BINARY_DIR}/${binary_type_latest}
       echo WinCoot-$wincoot_version > ${BINARY_DIR}/$binary_type_latest
       # finally copy files and update the build-status
       echo copy files from ${BINARY_DIR} to ${PUBLIC_BINARY_DIR}
       cp ${BINARY_DIR}/${wincoot_exe} ${PUBLIC_BINARY_DIR}/
       cp ${BINARY_DIR}/${wincoot_exe}.md5sum ${PUBLIC_BINARY_DIR}/
       cp ${BINARY_DIR}/${binary_type_latest} ${PUBLIC_BINARY_DIR}/
       cp $LOCAL_HTML_LOGS/gtk2-build-status $PUBLIC_HTML_LOGS/gtk2-build-status
       
   else
       echo Installer script failed! No windows installer made!
       echo fail-installer > $PUBLIC_HTML_LOGS/gtk2-build-status
   fi
else
   if [ "$build_installer" = "999" ] ; then
       echo WinCoot installer is up to date. Dont make a new one.
   else
       echo Not making installer since inconsistent versions/or build errors
       echo or failed tests
       #if [ "$coot_build_status" = "0" ] ; then
       #    echo pass-build > $PUBLIC_HTML_LOGS/gtk2-build-status
       #else
       #    echo fail-build > $PUBLIC_HTML_LOGS/gtk2-build-status
       #fi
	   # maybe just copy status?
       cp $LOCAL_HTML_LOGS/gtk2-build-status $PUBLIC_HTML_LOGS/gtk2-build-status
   fi
fi

# finally chmod of public dirs (not all necessary I think)
# not really working on msys right now
#chmod 755 /z/build-logs/MINGW32_NT-6.1-sarabellum
#chmod 744 /z/build-logs/MINGW32_NT-6.1-sarabellum/*
#chmod 744 /z/software/binaries/pre-release/*
#chmod 744 /z/software/binaries/stable/*
#chmod 755 /z/build-logs/MINGW32_NT-6.1-sarabellum/*
#chmod 744 /z/build-logs/MINGW32_NT-6.1-sarabellum/*/*
) 2>&1 > $HOME/20-wincoot-autobuild-all.txt
cp ${HOME}/20-wincoot-autobuild-all.txt ${PUBLIC_HTML_LOGS}

