#!/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=gdal-stable

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

svn checkout https://svn.osgeo.org/gdal/branches/1.5/gdal $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

# 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

./configure --prefix=/usr/local --with-libz=internal --with-png=internal --with-libtiff=internal --with-geotiff=internal --with-jpeg=internal --with-gif=internal --with-geos=yes --with-pg=/usr/bin/pg_config --with-sqlite=/usr/local/lib --with-xerces=yes --with-python --without-ogpython --with-curl --with-hdf4 --with-threads=yes --mandir=/usr/local/share/man 2>&1 | tee log.configure

# --with-hdf4=/usr/local/lib # nie dizała na amd64

make 2>&1 | tee log.make
make man 2>&1 | tee log.make_man

# 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 make install install-man 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}

#echo "NOW: sudo dpkg -i $dir_deb/${working}_${ver}-1_${arch}.deb; sudo ldconfig"
#echo "NOW: sudo dpkg -i $dir_deb/${working}_${ver}-1_${arch}.deb; sudo ldconfig"

