#!/usr/bin/env bash

META_VERSION="$(grep '^version: ' Meta | cut -d' ' -f2)"
CHANGES_VERSION="$(grep -E '^version:' Changes | head -n1 | cut -f2 -d' ')"
[ -n "$CHANGES_VERSION" ] ||
  CHANGES_VERSION="$(grep -E '\- [0-9]' Changes | head -n1 | cut -f2 -d' ')"
OK=0

error() {
  echo "Error, can't release: $1" >&2
  OK=1
}

if ! (grep "^version: $META_VERSION" Changes &>/dev/null); then
  if ! (grep "^- $META_VERSION" Changes &>/dev/null); then
    error "No Changes entry for version '$META_VERSION'"
  fi
fi

if [ "$META_VERSION" != "$CHANGES_VERSION" ]; then
  error "Changes version ($CHANGES_VERSION) and Meta version ($META_VERSION) do not match"
fi

if [ -z "$(grep -r 'VERSION' lib | grep "$META_VERSION")" ]; then
  error "No '\$VERSION = $META_VERSION' statement in lib/"
fi

git tag | grep -E "^v?${META_VERSION//./\\.}$" &>/dev/null &&
  error "Version '$META_VERSION' already tagged as released"

branch_name=$(git symbolic-ref -q HEAD)
branch_name=${branch_name##refs/heads/}
branch_name=${branch_name:-HEAD}

if [ -z "$RELEASE_BRANCH" ]; then
  error "Can't deterine RELEASE_BRANCH"
elif [ "$branch_name" != "$RELEASE_BRANCH" ]; then
  error "Not on '$RELEASE_BRANCH' branch"
fi

[ "$OK" -ne 0 ] && exit $OK

if [ -n "$(git status -s)" ]; then
  git status
  if [[ "$(git status)" =~ $'\n'\#\ Untracked ]]; then
    error "Untracked files."
  fi
fi

exit $OK
