#!/bin/sh -e

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

usage() {
    cat >&2 <<EOF
Usage: %0 [options]
Generate a barnowl release tarball.

OPTIONS:
  -f            Don't require a changelog entry for the new release.
  --no-tag      Don't create and sign a git tag for the new release
  --git         Do a beta release for the current git revision.
EOF
}

force=
no_tag=
git=

for arg; do
    case $arg in
        -f) force=1 ;;
        --no-tag) no_tag=1 ;;
        --git) git=1 ;;
        -h|--help) usage ;;
    esac
done

if [ "$git" ]; then
    force=1
    no_tag=1
    VERS=$(git describe --match='barnowl-*' HEAD | sed s,^barnowl-,,)
else
    VERS=$(perl -ne 'print $1 if m{^AC_INIT\(\[[^\]]+\],\s*\[([^\]]+)\]}' configure.ac) \
        || die "Unable to parse barnowl version"
fi
TAG=barnowl-$VERS
TGZ="$TAG-src"

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

head=$(git symbolic-ref HEAD)
head=${head#refs/heads/}

git rev-parse --verify -q $head >/dev/null 2>&1
git rev-parse --verify -q origin/$head >/dev/null 2>&1
if [ -n "$(git rev-list $head..origin/$head)" ]; then
    die "$head is not up to date. 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"
[ "$git" ] && perl -i -pe 's{^(AC_INIT\(\[[^\]]+\],\s*)\[([^\]]+)\]}{${1}['$VERS']}' configure.ac
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 [wiki:release-notes/$VERS Release Notes] or [/browser/ChangeLog?rev=barnowl-$VERS ChangeLog].
EOF
