#!/bin/bash -e

########################################
# Make sure working directory is clean #
########################################
if [ ! -z "$(git status --porcelain)" ]; then
  echo Refusing to operate on unclean working directory
  echo Use \"git status\" to see which files have been modified
  exit 1
fi

#########################
# Determine the version #
#########################
current_version=$(node -p "require('./package').version")

if ! [[ $next_version ]]; then
  printf "Enter version or <ENTER> to release $current_version: "
  read next_version
fi

if ! [[ $next_version ]]; then
  next_version=$current_version
fi

if ! [[ $next_version =~ ^[0-9]\.[0-9]+\.[0-9](-.+)? ]]; then
  echo >&2 "Version \"$next_version\" is not valid! It must be a valid semver string like 1.0.2 or 2.3.0-beta.1"
  exit 1
fi

echo '############################################################'
echo '#              Cleaning up local directory                 #'
echo '############################################################'
yarn run clean

echo '############################################################'
echo '#          Running tests with coverage data                #'
echo '############################################################'
yarn run test:coverage

echo '############################################################'
echo '#                Building canvas-planner                   #'
echo '############################################################'
NODE_ENV=production BABEL_ENV=production yarn run build

############################################################
#               Fix package.json version                   #
############################################################
node -p "p=require(\"./package\");p.version=\"$next_version\";JSON.stringify(p,null,2)" > package.publishing.json
mv package.publishing.json package.json

echo '############################################################'
echo '#                   Publishing to npm                      #'
echo '############################################################'
npm publish

echo '############################################################'
echo '#                  Pushing release tag                     #'
echo '############################################################'
release_tag="v$next_version"
git tag -am "Version $next_version" $release_tag
git push origin $release_tag


echo '############################################################'
echo '            SUCCESSFULLY PUBLISHED   '$next_version
echo '############################################################'
