#!/bin/bash
set -eu

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

[ -e Makefile.in ] || autoreconf -fvi
[ -e config.status ] || ./configure
make -j4 distcheck VERSION="$VERS"

echo 'Checking distributed files against Git:'
if comm -3 <(tar -tzf "$TAG.tar.gz" | grep -v '/$' | sed "s%^$TAG/%%" | sort) \
    <(git ls-files | sort) | grep -vxf scripts/dist-ignore; then
    echo
    echo 'Error: Please fix Makefile.am and/or scripts/dist-ignore.'
    exit 1
fi
echo 'ok'

mv "$TAG.tar.gz" "$TGZ.tgz"

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

echo "Created release tarball for BarnOwl $VERS at $(pwd)/$TGZ.tgz"
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 read the [wiki:release-notes/$VERS release notes] or [/browser/ChangeLog?rev=barnowl-$VERS ChangeLog].
EOF
