#!/bin/sh -e

die() {
    echo "$@" >&2
    exit 1
}

force=
no_tag=

for arg; do
    case $arg in
        -f) force=1 ;;
        --no-tag) no_tag=1 ;;
    esac
done

VERS=$(perl -ne 'print $1 if m{^AC_INIT\(\[[^\]]+\],\s*\[([^\]]+)\]}' configure.ac) \
    || die "Unable to parse barnowl version"
TAG=barnowl-$VERS
TGZ="$TAG-src"

if [ ! "$force" ] && [ "$VERS" != "$(head -1 ChangeLog)" ]; then
    die "No ChangeLog entry for version $VERS, aborting."
fi

if ! [ "$no_tag" ]; then
    if git cat-file -t "$TAG" > /dev/null 2>&1; then
        die "Error: Object $TAG already exists."
    fi

    git tag -s -m "BarnOwl $VERS" "$TAG"
else
    TAG=HEAD
fi

exittrap() { :; }
for sig in 1 2 13 15; do trap "exit $(($sig + 128))" $sig; done
trap 'exittrap' EXIT

TMPDIR=$(mktemp -d /tmp/barnowl.XXXXXX)

exittrap() { rm -rf "$TMPDIR"; }

git archive --format=tar --prefix="$TGZ/" "$TAG" | tar -x -C "$TMPDIR"

CODIR=$(pwd)
cd "$TMPDIR/$TGZ"
autoreconf -fvi
cd "$TMPDIR"
tar czvf "$TGZ.tgz" "$TGZ"
cd "$CODIR"

mv "$TMPDIR/$TGZ.tgz" .
rm -rf "$TMPDIR"

exittrap() { :; }

echo "Created release tarball for BarnOwl $VERS in $(pwd)"
echo "Remember to bump OWL_VERSION_STRING for future development."

COMMIT=$(git rev-parse "$TAG")
NOW=$(date +"%B %d, %Y")
cat <<EOF
 * '''$NOW''': BarnOwl $VERS Released. [wiki:Download] it here. or see the [/browser/ChangeLog?rev=$COMMIT ChangeLog]
EOF
