#!/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
}

prompt() {
  local msg answer default yn=false
  case $# in
    0) msg="${prompt_msg:-Press <ENTER> to continue, or <CTL>-C to exit.}" ;;
    1)
      msg="$1"
      if [[ "$msg" =~ \[yN\] ]]; then
        default=n
        yn=true
      elif [[ "$msg" =~ \[Yn\] ]]; then
        default=y
        yn=true
      fi
      ;;
    2)
      msg="$1"
      default="$2"
      ;;
    *) die "Invalid usage of prompt" ;;
  esac
  while true; do
    read -p "$msg" answer
    [ $# -eq 0 ] && return 0
    [ -n "$answer" -o -n "$default" ] && break
  done
  if "$yn"; then
    [[ "$answer" =~ ^[yY] ]] && echo y && return 0
    [[ "$answer" =~ ^[nN] ]] && echo n && return 0
    echo "$default"
    return 0
  fi
  if [ -n "$answer" ]; then
    echo "$answer"
  else
    echo "$default"
  fi
}

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' | 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 [ "$branch_name" != master ]; then
  error "Not on 'master' branch"
fi

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

if [ -n "$(git status -s)" ]; then
  git status
  if [[ "$(git status)" =~ $'\n'\#\ Untracked ]]; then
    error "Untracked files."
  else
    prompt "Uncommitted changes. Commit them and continue? (Enter or CTRL-C) " 1
    git commit -a -m "$META_VERSION"
  fi
fi

exit $OK
