#!/bin/bash

set -u #exit the script if an uninitialised variable is used
set -e #exit the script if any statement returns a non-true return value
set -o pipefail #exit if there's an error before the pipe

exitprocedure()
{
 echo "User break!"
 exit 1
}

trap "exitprocedure" 2 3 15

# Set locale to C so that the log files are in English:
LC_ALL=C
export LC_ALL

# Source the script with variables that define paths and arch:
source build_vars.sh

# What are we building?
working=grass64

mkdir -p $dir_src/$working
mkdir -p $dir_bld/$working

svn checkout https://svn.osgeo.org/grass/grass/branches/develbranch_6 $dir_src/$working 2>&1 | tee $dir_src/$working/log.svn

# The following will cleaunp the source where the build takes place
# (kindoff "make distclean") and transfer newer files at the same time:
rsync -a --delete --stats $dir_src/$working $dir_bld 2>&1 | tee $dir_src/$working/log.rsync
#echo "heja heja"
#read a

# Move logs into the build dir (let's keep all logs in the same dir and not pollute the
# original source code tree):
mv $dir_src/$working/log.rsync $dir_bld/$working/
rm $dir_src/$working/log.svn

cd $dir_bld/$working

#debugging:
#CFLAGS="-g -Wall"
#LDFLAGS=""
#export CFLAGS
#export LDFLAGS

# patch na dostęp do mapsetów po userach
#patch ${dir_bld}/${working}/lib/gis/mapset_msc.c < ${dir_src}/grass_addons/mapset_msc.c.diff

./configure --prefix=/usr/local --with-cxx --without-odbc --with-sqlite --with-tcltk-includes="/usr/include/tcl8.4/" --with-postgres --with-postgres-includes="/usr/include/postgresql/" --with-freetype --with-freetype-includes="/usr/include/freetype2/" --with-readline --with-proj-share=/usr/share/proj/ --with-python --with-wxwidgets --with-cairo --enable-64bit 2>&1 | tee log.configure
# --with-ffmpeg --with-ffmpeg-includes=/usr/include/ffmpeg/
# --with-wxwidgets
# --with-cairo
# --enable-64bit

make 2>&1 | tee log.make

# Remove any spec files - they might interfere with checkinstall:
rm -f *.spec

rev=`grep "Checked out revision [[:digit:]]\{1,\}\." $dir_bld/$working/log.svn | grep -o "[[:digit:]]\{1,\}"`
ver=`date +%F`"-${rev}"

sudo checkinstall -D -y --pkgname=$working --pkgversion=$ver --strip=no --stripso=no --pakdir=$dir_deb --deldoc=yes --deldesc=yes --delspec=yes --backup=no --fstrans=no --install=yes 2>&1 | tee log.checkinstall
sudo ldconfig

# In case running checkinstall as root left some root owned files or dirs,
# change their owner to USER so we don't run into errors at next script
# runtime when rsync is called:
sudo chown -R ${USER}:${USER} ${dir_bld}/${working}

# build gdal-grass:

cvs_gdal-grass

