#!/bin/sh

#$1 is --version
version="$2"
file="$3"

if echo "$file" | grep -qvF '.tar.'; then
	if echo "$version" | grep -q '\.'; then
		#version
		git_version=ctdb-$version
	else
		#commithash or branch
		git_version="$version"
		version=0.0.0+git0
	fi

	echo "Downloading from git ..."
	#pull source from git
	git clone git://git.samba.org/ctdb.git ctdb-tmp
	cd ctdb-tmp
	git checkout "$git_version"
	cd ..
	if echo "$2" |  grep -qv '\.'; then
		#construct version with latest release+git0
		version=`grep -A 1 '%changelog' ctdb-tmp/packaging/RPM/ctdb.spec.in | tail -n1 | sed 's/.* \([0-9\.-]\+\)$/\1/'`+git0
	fi
	mv ctdb-tmp "ctdb-$version.dfsg"
	#clean source
	rm -rf "ctdb-$version.dfsg/.git"
else
	echo "Using provided tarball"
	tar -xzf "$file"
	mv "ctdb-$version" "ctdb-$version.dfsg"
fi

# Remove original file
rm -f "$file"

#autogen
cd "ctdb-$version.dfsg"
./autogen.sh
cd ..

#remove included popt, tdb, talloc, tevent
rm -rf "ctdb-$version.dfsg/lib/popt"
rm -rf "ctdb-$version.dfsg/lib/tdb"
rm -rf "ctdb-$version.dfsg/lib/talloc"
rm -rf "ctdb-$version.dfsg/lib/tevent"

#tar.gz
tar cfz "$file" "ctdb-$version.dfsg"

#remove source directory
rm -rf "ctdb-$version.dfsg"

