#!/bin/sh
set -e
if [ -z "$1" ]
  then
    echo "You must specify a branch to merge."
    exit 1
fi
if [ -z "$2" ]
  then
    echo "You must specify a version."
    exit 1
fi
if [ ! -z "$(git status --untracked-files=no --porcelain)" ]; then
  echo 'The working directory must be clean to run this script.'
  echo 'Please commit or stash your changes.'
  exit 1
fi
export BRANCH="$1"
export TAG="$2"
export VERSION=`echo "$2" | sed 's/^v//g'`
export MSG="Release version $TAG"
export CURRENT_BRANCH=`git rev-parse HEAD`
python3 - << EOF
import json

pkg = json.loads(open('package.json', 'r').read())
pkg['version'] = "$VERSION"
with open('package.json', 'w') as f:
    f.write(json.dumps(pkg, sort_keys=True, indent=2))
EOF
if [ ! $BRANCH='HEAD' ];
then
  GIT_MERGE_AUTOEDIT=no git merge --no-ff --signoff "$BRANCH"
fi
echo "Merging branch $BRANCH and releasing version $TAG"
echo "To undo this operation, invoke the following command\n"
echo "\tgit reset --hard $CURRENT_BRANCH && git tag -d $TAG\n"
git add package.json
if [ ! $BRANCH='HEAD' ];
then
  git commit --amend --no-edit
else
  # Do not amend the package.json commit to the current commit
  # if we are releasing from HEAD, since it may already be
  # pushed to the remote (in which case an amend causes the
  # update to be rejected).
  git commit -m "$MSG" --signoff
fi
git tag "$TAG" -m "$MSG"
git push && git push --tags
if [ ! $?="0" ];
then
  git reset --hard $CURRENT_BRANCH && git tag -d $TAG
fi
