#!/bin/bash
# NOTE: this script is a stopgap this sort of thing might be better done with a
#       semantic release type work flow however there are complexities with
#       the way we use git for publishing modules.

set -e

usage() {
  echo ""
  echo "tsm publish usage:"
  echo "=================="
  echo ""
  echo "  tsm publish <semvertype>"
  echo ""
  echo "Where semvertype can be one of the following list:"
  echo ""
  echo "  patch|minor|major"
  echo ""
}

version() {
  PACKAGE_VERSION=$(cat package.json \
  | grep version \
  | head -1 \
  | awk -F: '{ print $2 }' \
  | sed 's/[",]//g' \
  | tr -d '[[:space:]]')

  echo $PACKAGE_VERSION
}

# Need bash >= 3 for guarding below
if ((BASH_VERSINFO[0] < 3)); then echo "Sorry, you need at least bash-3.0 to run this script." >&2; exit 1; fi

# accept input patch | minor | major
if ! [[ "$1" =~ ^(patch|minor|major)$ ]]; then
  usage
  exit 1
fi

# ensure master branch
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [[ "$BRANCH" != "master" ]]; then
  echo 'Not on master branch aborting publish';
  exit 1;
fi

if [ -n "$(git status --porcelain)" ]; then
  echo "This branch is dirty";
  exit 1;
fi

# ensure local master is the same as remote master
if [[ "$(git rev-parse @)" != "$(git rev-parse @{u})" ]]; then
  echo "This branch is not upto date with remote master"
  exit 1
fi

yarn build

# update package.json and commit to git
yarn version --$1

# NOTE: There are issues to work through here around PR worlflow leaving this for now

# push tags
git push --tags
