#! /bin/sh

# This file is POSIX sh. No bash-specific syntax, please.

set -ex

version=$1
case $version in v*|*[/:-]*)
	echo "Invalid version '$version'" >&2
	exit 2
;; [0-9]*)
	# ok
;; *)
	echo "Usage: $0 <version>" >&2
	exit 2
esac

if [ -t 1 ]
then
	echo "You must redirect the output of this command to a file." >&2
	exit 2
fi

# check if we're in the right directory
test -e setup.py

umask 002

tmp=$(mktemp -d)
trap 'rm -rf -- "$tmp"' EXIT INT HUP TERM QUIT

version_tags=$(git tag | grep '^v[0-9]')

git archive --prefix=eloquent-$version/ v$version |
	tar xC "$tmp"

# Only for testing purposes:
#mkdir "$tmp/eloquent-$version"
#cp -a * "$tmp/eloquent-$version/"

git log --pretty=tformat:"%H %s" v$version >$tmp/eloquent-$version/Release_Notes.txt

(
	cd $tmp/eloquent-$version

	# Check if all version tags are listed in the changelog:
	debian_versions=$(sed -rn 's/^[^ ]+ \(([^ )]+)\) .*/\1/p' <debian/changelog)
	for tag in $version_tags
	do
		case "$IFS$debian_versions$IFS" in *[$IFS]${tag#v}[$IFS]*) ;; *)
			echo "Version tag $tag not listed in debian/changelog" >&2
			exit 2
		esac
	done

	debuild -us -uc
) >&2

cd "$tmp"

tar c *.deb *.dsc *.tar.xz
