#!/bin/bash
# Latest git build procedure for a particular version of CMake.
# Typical usage:

#./git_build.sh 3.10.0-rc2 no

# where the first argument is the cmake version string, and
# only if the second argument is "yes" is the optional
# install symlink created.

# Number of parallel jobs should be same as number of hardware threads (16 for a Ryzen 7 1700 system)
# to get the maximum efficiency out of those threads.
JOBS=16

export CMAKE_VERSION=$1
echo "Build CMake ${CMAKE_VERSION}"

export if_symlink=$2
if [ "$if_symlink" = "yes" ] ; then
    echo "A /home/software/cmake/install symlink will be created"
else
    echo "A /home/software/cmake/install symlink will NOT be created"
fi

TAG_VERSION=v${CMAKE_VERSION}
export CFLAGS='-O3'
export CXXFLAGS='-O3'

# Use this directory as a convenient prefix directory for
# all directories below.
cd /home/software/cmake
PREFIX_DIRECTORY=$(pwd)

# Update master branch of local repository
cd ${PREFIX_DIRECTORY}/cmake.git
git checkout release
git fetch
git merge --ff-only origin/release

# Check TAG_VERSION from local updated git repository
git tag --verify ${TAG_VERSION}

# Checkout TAG_VERSION from local updated git repository
git checkout ${TAG_VERSION}

mkdir -p ${PREFIX_DIRECTORY}/build_dir
cd ${PREFIX_DIRECTORY}/build_dir
# Use fresh start every time
rm -rf ${PREFIX_DIRECTORY}/build_dir/* ${PREFIX_DIRECTORY}/install-${CMAKE_VERSION}
echo "Bootstrapping the cmake build.  This may take a while...."  
nice -19 ${PREFIX_DIRECTORY}/cmake.git/bootstrap \
--prefix=${PREFIX_DIRECTORY}/install-${CMAKE_VERSION} \
--parallel=$JOBS --qt-gui --system-curl  >& bootstrap.out

echo "Building cmake.  This may take a while..."
nice -19 make -j$JOBS >& make.out
echo "Installing cmake."
nice -19 make -j$JOBS install >& make_install.out

echo "Check for all warnings"
grep -i warning *.out
# N.B. currently there is a warning about COPY_ONLY (which should be
# COPYONLY) in
# /usr/lib/x86_64-linux-gnu/cmake/Qt5Core/Qt5CoreMacros.cmake:224.
# That file belongs to qtbase5-dev:amd64 whose version is
# 5.3.2+dfsg-4+deb8u1, but (see
# <https://bugreports.qt.io/browse/QTBUG-44637>) apparently this Qt5
# bug has been fixed in 5.4.1.

echo "Check for all errors"
grep -i error *.out
# N.B. got errors at this stage until I installed libqt4-dev (and
# qt4-doc and qt4-dev-tools).
cd ${PREFIX_DIRECTORY}

if [ "$if_symlink" = "yes" ] ; then
    rm -f install
    ln -s install-${CMAKE_VERSION} install
fi
