#!/bin/bash

if [ $# -ne 1 ]
then
	echo "Usage: `basename $0` {version}"
	exit 1
fi

DOTTED_VERSION=$1
SLASHED_VERSION=$(echo $DOTTED_VERSION|sed 's/\./_/g')
OLD_WORKING_DIR=`pwd`
WORKING_DIR=/tmp/libsysactivity-$RANDOM

clean () {
	rm -rf $WORKING_DIR
}

mkdir -p $WORKING_DIR
cd $WORKING_DIR

git clone git://libsysactivity.git.sourceforge.net/gitroot/libsysactivity/libsysactivity -b v${DOTTED_VERSION%.*} libsysactivity-$DOTTED_VERSION
cd libsysactivity-$DOTTED_VERSION
git checkout v$DOTTED_VERSION
cd ..

grep -r --color "	printf" $WORKING_DIR/libsysactivity-$DOTTED_VERSION/src/*
if	[ $? == 0 ]; then
	echo "There are printf() calls in the code"
	clean
	exit 2
fi

grep LIBSA_VERSION $WORKING_DIR/libsysactivity-$DOTTED_VERSION/CMakeLists.txt
read -p "Have you updated the CMakeList.txt version? (y/n) " yn
if	[ $yn != "y" ]; then
	clean
	exit 2
fi

grep SA_VERSION_ $WORKING_DIR/libsysactivity-$DOTTED_VERSION/src/common/global.h
read -p "Have you updated the version in global.h? (y/n) " yn
if	[ $yn != "y" ]; then
	clean
	exit 2
fi

grep PROJECT_NUMBER $WORKING_DIR/libsysactivity-$DOTTED_VERSION/Doxyfile
read -p "Have you updated the Doxyfile version? (y/n) " yn
if	[ $yn != "y" ]; then
	clean
	exit 2
fi

cat $WORKING_DIR/libsysactivity-$DOTTED_VERSION/cmake/libsysactivityConfigVersion.cmake
read -p "Have you updated the libsysactivityConfigVersion.cmake? (always needed) (y/n) " yn
if	[ $yn != "y" ]; then
	clean
	exit 2
fi

head $WORKING_DIR/libsysactivity-$DOTTED_VERSION/CHANGELOG
read -p "Have you updated the changelog? (y/n) " yn
if	[ $yn != "y" ]; then
	clean
	exit 2
fi

grep LIBSA_ABI_VERSION $WORKING_DIR/libsysactivity-$DOTTED_VERSION/src/CMakeLists.txt
read -p "Did you break the ABI? (y/n) " yn

for dir in DragonFly FreeBSD Linux NetBSD OpenBSD SunOS
do
	cppcheck --error-exitcode=1 -I $WORKING_DIR/libsysactivity-$DOTTED_VERSION/src/common/ -I $WORKING_DIR/libsysactivity-$DOTTED_VERSION/src/$dir/ $WORKING_DIR/libsysactivity-$DOTTED_VERSION/src/$dir/*.c
	if	[ $? != 0 ]; then
		echo "ERROR: cppcheck found an error on $dir code."
		clean
		exit 3
	fi
done

mkdir $WORKING_DIR/libsysactivity-$DOTTED_VERSION/build/
cd $WORKING_DIR/libsysactivity-$DOTTED_VERSION/build/

cmake .. -DCMAKE_BUILD_TYPE=debug && make
if	[ $? != 0 ]; then
	echo "ERROR: Can't build the CVS code."
	clean
	exit 4
fi

make -f test/Makefile && make test
if	[ $? != 0 ]; then
	echo "ERROR: Unit tests not passed."
	clean
	exit 5
fi
rm -rf $WORKING_DIR/libsysactivity-$DOTTED_VERSION/build/*
rm -rf $WORKING_DIR/libsysactivity-$DOTTED_VERSION/.git*

cd $WORKING_DIR
tar -zcvf libsysactivity-$DOTTED_VERSION.tar.gz libsysactivity-$DOTTED_VERSION

mv libsysactivity-$DOTTED_VERSION.tar.gz ~
cd $OLD_WORKING_DIR

clean
