#!/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/sentinella-$RANDOM

clean () {
	rm -rf $WORKING_DIR
}

mkdir -p $WORKING_DIR
cd $WORKING_DIR

git clone git://git.code.sf.net/p/sentinella/code -b v${DOTTED_VERSION%.*} sentinella-$DOTTED_VERSION
cd sentinella-$DOTTED_VERSION
git checkout v$DOTTED_VERSION
cd ..

read -p "Have you updated the version in main.cpp? (y/n) " yn
if  [ $yn != "y" ]; then
	clean
	exit 2
fi

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

mkdir $WORKING_DIR/sentinella-$DOTTED_VERSION/build
cd $WORKING_DIR/sentinella-$DOTTED_VERSION/build/
cmake .. -DCMAKE_BUILD_TYPE=debug && make
if	[ $? != 0 ]; then
	echo "ERROR: Can't build the git code."
	clean
	exit 4
fi
rm -rf $WORKING_DIR/sentinella-$DOTTED_VERSION/build/*
rm -rf $WORKING_DIR/sentinella-$DOTTED_VERSION/.git*

chmod -x $WORKING_DIR/sentinella-$DOTTED_VERSION/src/Actions/*
chmod -x $WORKING_DIR/sentinella-$DOTTED_VERSION/src/Conditions/*

cd $WORKING_DIR
tar -c --xz -f sentinella-$DOTTED_VERSION.tar.xz sentinella-$DOTTED_VERSION

mv sentinella-$DOTTED_VERSION.tar.xz ~
cd $OLD_WORKING_DIR

clean
