#!/bin/sh

set -e

source functions.sh

cd /home/rusconi/devel

thisDir=$(pwd)

##########################################################################
# Grab the version of the source package and construct the name of the 
# source tarball that we'll need.

cd massxpert || { echo "Failed to change directory to massxpert"; exit 1; }

VERSION=$(sourceVersion)
srcTarballName=massxpert-${VERSION}.tar.gz
echo "Tarball name: ${srcTarballName}"

##########################################################################


##########################################################################
# Begin make sure that the documentation is ok

cd usermanual


# First ensure all the subdocuments are inputted in master tex file.

checkUsermanualIntegrity || { echo "The User Manual does not include all subdocuments"; exit 1; }


# Second, make sure that the version of the user manual matches the
# version of the source package.

if [ $(usermanualVersion) != "${VERSION}" ]
    then
    echo "User Manual has version different than Source package"
    exit 1
fi


# Finally make the User Manual documentation (pdf first and html next)
echo "Compiling Usermanualual"

makeUsermanualPdf  || { echo "Failed to compile the User Manual PDF."; exit 1; }

# End make sure that the documentation is ok
##########################################################################


##########################################################################
# Clean the usermanual build, because the debian package orig tarball 
# should have to build doc.

# NOTE THAT BECAUSE WE ARE BUILDING AN RPM PACKAGE, WE DO NOT REMOVE
# THE COMPILED USERMANUAL !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# echo "current directory: $(pwd)"
# make -f Makefile maintainerclean

# Go back to the parent directory
cd ${thisDir}

# At this point we are in /home/rusconi/devel.

# Remove ~/tmp/massxpert-${VERSION} if it exists
rm -rf ~/tmp/massxpert-${VERSION}

# Create source tarball in /tmp
makeSourceTarball ${srcTarballName} || { echo "Failed to prepare source tarball."; exit 1; }

echo "Produced source tarball ${srcTarballName}" ; sleep 2

# Go back to the parent directory
cd ${thisDir}

sudo cp -v ~/tmp/${srcTarballName} /usr/src/redhat/SOURCES
sudo cp -v ~/devel/massxpert/massxpert.spec /usr/src/redhat/SPECS

cd /usr/src/redhat/SPECS || { echo "Failed to change dir to /usr/src/redhat/SPECS."; exit 1; }

echo "Starting rpmbuild -ba massxpert.spec in $(pwd)"

sudo rpmbuild -ba massxpert.spec || { echo "Failed to create the rpm package."; exit 1; }

cp /usr/src/redhat/RPMS/i386/massxpert-${VERSION}-1.fc8.i386.rpm ~/tmp

cd ~/tmp

rm -rf ~/tmp/usr

rpm2cpio massxpert-${VERSION}-1.fc8.i386.rpm | cpio -iv --make-directories


