#!/bin/bash --norc

# Copyright (c) 2015, the Dart Team. All rights reserved. Use of this
# source code is governed by a BSD-style license that can be found in
# the LICENSE file.

warning_at_entry () {
  echo 'NB: This script is highly specialized, it is only intended to be used'
  echo 'when a new version of the reflectable package is being published.'
  echo 'The procedure can be stopped at every step by pressing ^C rather'
  echo 'than [ENTER].'
  echo
}

usage () {
  warning_at_entry
  echo "Usage:"
  echo "  $0 [--help|-h] [<new-version>]"
  echo "where <new-version> = <major-number>.<minor-number>.<patch-number>"
}

ensure_int () {
  if [[ $1 = 0 ]]; then return; fi
  if [[ $1 =~ ^[1-9][0-9]*$ ]]; then return; fi
  usage
  echo
  echo "Received '$1', expected an integer"
  exit -1
}

edit_version () {
  TMPFILE=`tempfile`
  mv $1 $TMPFILE
  sed -e "s/^version: .*$/version: $2/" <$TMPFILE >$1
}

while [[ $1 =~ ^- ]]; do
  case $1 in
    (--help|-h) usage; exit 0;;
    (*) usage; exit -1;;
  esac
done

if [ "$#" -ne "1" ]; then
  usage
  exit -1
fi

if [[ ! `pwd` =~ /tool$ ]]; then
  echo "This script must be executed from the 'tool' subdirectory of"
  echo "the root directory of the package reflectable."
  exit -1
fi

if git status | head -1 | grep master >/dev/null; then
  echo "On branch master; please create a fresh branch for publishing."
  exit -1
fi

if [ "`git diff master | wc -l`" -ne "0" ]; then
  echo "On a branch that differs from master; please create a fresh"
  echo "branch for publishing."
  exit -1
fi

MAJOR="${1%%.*}"
MINOR="${1#*.}"; MINOR="${MINOR%.*}"
PATCH="${1##*.}"

ensure_int $MAJOR
ensure_int $MINOR
ensure_int $PATCH

warning_at_entry

VERSION="$MAJOR.$MINOR.$PATCH"
TAG_VALUE="v$VERSION"
COMMIT_MESSAGE="'Bumping version to $VERSION'"
TAG_MESSAGE="'Released as version $VERSION'"

echo "Using tag value '$TAG_VALUE'."
echo -n "Update CHANGELOG.md and then press [ENTER] here to see the diff.. "
read

edit_version ../pubspec.yaml $VERSION

git diff HEAD

( cd ..; pub publish --dry-run )
echo ">>>>>> Run these commands:"
echo git add --all
echo git commit -m$COMMIT_MESSAGE
echo git push --set-upstream origin "current_branch_name"
echo ">>>>>> Please get review such that these changes can be landed.. "
echo ">>>>>> Merge the PR on github"
echo git co master
echo git pull --rebase origin master
echo pushd ..
echo pub publish
echo git tag -a -m$TAG_MESSAGE $TAG_VALUE
echo git push origin refs/tags/$TAG_VALUE:refs/tags/$TAG_VALUE
echo popd
