#!/bin/bash

# run as: ./makegs2.sh [gnome-lib] [imagemagick]
# If gnome-lib passed in, will compile GS2 using gnome-lib 
# which checks out gnome-lib src from svn if possible and if needed (if no ext/gnome-lib-minimal)
# If you pass in imagemagick, it will grab the appropriate linux/darwin binary, untar
# this and put its OS subfolder renamed as imagemagick into the bin/os folder.

# Note, Mac (darwin) machines don't always display all env vars on doing env/printenv, 
# e.g. DYLD_LIBRARY_PATH and DYLD_FALLBACK_LIBRARY_PATH are hidden
# To display hidden vars follow:
# http://www.commandlinefu.com/commands/view/6899/print-all-environment-variables-including-hidden-ones
# but remove capital T from command, making: for _a in {A..Z} {a..z};do _z=\${!${_a}*};for _i in `eval echo "${_z}"`;do echo -e "$_i: ${!_i}";done;done|cat -Tsv
# into: for _a in {A..Z} {a..z};do _z=\${!${_a}*};for _i in `eval echo "${_z}"`;do echo -e "$_i: ${!_i}";done;done|cat -sv
# Can redirect the output of the command into files and do a diff to see difference in environment.

getgnomelib=
getimagick=

# https://stackoverflow.com/questions/20449680/unix-boolean-operators-a-o
if [[ "x$1" == "xgnome-lib" ]]; then 
    getgnomelib=$1
elif [[ "x$1" == "ximagemagick" ]]; then 
    getimagick=$1
fi

if [[ "x$2" == "xgnome-lib" ]]; then 
    getgnomelib=$2
elif [[ "x$2" == "ximagemagick" ]]; then 
    getimagick=$2
fi

if [ "x$getgnomelib" != "x" ]; then
    echo "Will be getting gnomelib"
fi
if [ "x$getimagick" != "x" ]; then
    echo "Will be getting imagemagick"
fi

if [[ "x$getgnomelib" == "x" && "x$getimagick" == "x" ]]; then
    echo "Launching with no args"
fi

gsdlhome=`pwd`
echo "**** GSDLHOME: $gsdlhome"

bitness=`uname -m`
# if we're 64 bit, add -fPIC to CFLAGS. Check if bitness contains substring "64"
#if [[ $bitness == *"64"* ]]; then
#  export CFLAGS="-fPIC $CFLAGS"
#  echo "64 bit unix system, incl -fPIC in CFLAGS so it is now: $CFLAGS"
#fi

# Ever since around MacOS version Monterey, warnings about functions not pre-declared with extern
# are turned into errors instead when compiling. We want them behaving like warnings again.
# To do so, we set -Wno-error=implicit-function-declaration 
if test "$GSDLOS" = "darwin"; then
    if test "x$CFLAGS" = "x" ; then
	CFLAGS="-Wno-error=implicit-function-declaration"
    else
	CFLAGS="-Wno-error=implicit-function-declaration $CFLAGS"
    fi
    export CFLAGS
fi

# Compile by chaining the commands with && so it stops at that stage after an error
cd $gsdlhome
if [ "x$getgnomelib" = "xgnome-lib" ]; then
    ./configure --enable-gnome-lib-ext --enable-apache-httpd \
	&& make \
	&& make install
else
    ./configure --enable-apache-httpd \
	&& make \
	&& make install
fi

status=$?
echo "****************************************"
if [ $status = 0 ] ; then
    # 5. Message to warn user that the env of this x-term uses gnome-lib 
    # and GUIs may not work from this console
    if [ "x$getgnomelib" = "xgnome-lib" ]; then
	echo "*** The environment for this console has been set to compile Greenstone with gnome-lib."
	echo "*** As a result, graphical applications may not work well."
	echo "*** In such a case, open a new console."
    else
	echo "Finished compiling Greenstone2. (Compiled without gnome-lib)"
    fi
else
    echo "@@@ Error compiling up Greenstone. Return status: $status"
fi
#if [[ $bitness == *"64"* ]]; then
#    echo ""
#    echo "This unix is 64 bit. So added -fPIC to CFLAGS, which is now: $CFLAGS"
#fi
echo "****************************************"    

# Get the imagemagick precompiled binary for the OS system if compilation was successful
if [[ "$status" == "0" && "x$getimagick" == "ximagemagick" ]]; then    

    imgpkg=
    
    os=`uname`

   if [ "x$os" = "xDarwin" ]; then
       # The imagemagick binary built on El Capitan (10.11) was made backwards compatible up to and including Mountain Lion (10.8) using the mmacosx-version-min flag.
       # The kernel version of Mountain Lion is 12.6.0. For El Capitan it's 15.6.0
       # So any kernel version less than 12, we'll use the Leopard (10.5) imagemagick binary, and for greater, we'll use the El Capitan imgmagick binary
    
       # by default on Macs, will resort to the MountainLion-and-later compatible ElCapitan binary
       imgpkg=http://trac.greenstone.org/export/head/gs2-extensions/imagemagick/trunk/imagemagick-darwin-10.11.tar.gz

       kernelVersion=`uname -r`
       
       # kernel version is something like 15.6.0, need the major version number to do integer (not float) comparisons

       # https://stackoverflow.com/questions/20348097/bash-extract-string-before-a-colon
       # doesn't work, even when put into backticks:
       # majorKernelVersion=sed 's/\..*//'
       
       # Using pure bash solution to substring before first period mark
       # NOTE: two percent signs gets chars up to the first occurrence of period mark. Single percent sign gets chars up to last period mark.
       majorKernelVersion=${kernelVersion%%\.*}
       echo "MacOS major kernel version: $majorKernelVersion"

       # bash evaluates string as integer/vice-versa depending on context
       # https://unix.stackexchange.com/questions/232384/argument-string-to-integer-in-bash
       # http://tldp.org/LDP/abs/html/comparison-ops.html

       # El Capitan is MacOS version 10.11 but its kernelVersion is 15.6.0
       # For MacOS versions older than Mountain Lion/10.8 (kernel 12.6.0) use the Mac Leopard (10.5) imagemagick binary
       if [ "$majorKernelVersion" -lt "12" ]; then
	   echo "Getting imagemagick built on Mac Leopard"
	   imgpkg=http://trac.greenstone.org/export/head/gs2-extensions/imagemagick/trunk/imagemagick-darwin-10.5.tar.gz
       else
	   echo "Getting imagemagick built for El Capitan 10.11 (15.6.0) that's compatible with Mountain Lion 10.8 (kernel v 12.6.0) and onwards"
       fi

       pushd ext
       curl $imgpkg > imagemagick.tar.gz
       tar -xzf imagemagick.tar.gz
       rm -rf ../bin/darwin/imagemagick
       mv imagemagick/darwin ../bin/darwin/imagemagick
       popd

   else
       # linux
       pushd ext
       if [[ $bitness == *"64"* ]]; then
	   echo "Getting 64 bit imagemagick precompiled binary"
	   wget http://trac.greenstone.org/export/head/gs2-extensions/imagemagick/trunk/imagemagick-linux-x64.tar.gz
	   tar -xzf imagemagick-linux-x64.tar.gz
       else
	   echo "Getting 32 bit imagemagick precompiled binary"
	   wget http://trac.greenstone.org/export/head/gs2-extensions/imagemagick/trunk/imagemagick-linux.tar.gz
	   tar -xzf imagemagick-linux.tar.gz
       fi
 
       rm -rf ../bin/linux/imagemagick
       mv imagemagick/linux ../bin/linux/imagemagick
       popd
   fi

   # the setup script in the ext/imagemagick folder clashes with wget because it sets DYLD(_FALLBACK)_LIBRARY_PATH
   # on sourcing GS2's setup.bash. Since we're not using the imagemagick in the ext folder for GS2, as the 
   # precompiled imagemagick binary is moved into GS2/bin/OS, in a GS2 bin release and now here too (in a compiled GS2),
   # we can remove ext/imagemagick. The env vars it sets refer to the ext/imagemagick folder anyway, which we don't use
   # for our GS2 binaries, or for GS2 compiled versions using the precompiled imagemagick binary, as imagemagick will
   # live in GS2/bin/OS in such cases..
   rm -rf ext/imagemagick
   rm -rf ext/imagemagick.tar.gz   
fi


# PDFv2Plugin needs PDFBoxConverter extension, which doesn't come installed in GS2 by default
# But without it, the PDFv2Plugin won't work and pluginfo.pl -describeall will break,
# GLI will have issues launching. So repeat what the GS2 installer does:
# rename PDFv2Plugin.pm to PDFv2Plugin.tmp and show user a message on how to make it functional.
echo ""
echo "   Renaming PDFv2Plugin to make it unfunctional."
echo "   To make it functional, install the PDFBoxConverter extension for Greenstone"
echo "   and then rename the PDFv2Plugin.tmp file to PDFv2Plugin.pm"
echo ""
mv perllib/plugins/PDFv2Plugin.pm perllib/plugins/PDFv2Plugin.tmp

