#!/bin/bash

set -e

GITHUB_ORG='grouparoo'
GITHUB_REPO='grouparoo'

if [[ -z "$GITHUB_AUTH" ]];then
  echo "No GITHUB_AUTH, exiting.."
  exit 0;
fi

if [ -f ~/.npmrc ]; then
    echo "using local NPM user..."
else
    if [[ -z "$NPM_TOKEN" ]];then
      echo "No NPM_TOKEN or ~/.npmrc, exiting.."
      exit 0;
    else
      echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc
    fi
fi

# Push new version & tags to git with lerna
OLD_VERSION=`cat lerna.json | jq -r '.version'`
BRANCH=`git rev-parse --abbrev-ref HEAD`
echo "on $BRANCH branch"
if [[ $BRANCH == 'master' ]];
then
  npm run version-alpha
  PRERELEASE='true'
fi

if [[ $BRANCH == 'stable' ]];
then
  npm run version-stable
  PRERELEASE='false'
fi

# only publish if we match a tag directly (ie: 'v1.2.3'); i.e. the lerna version command succeded
git describe --exact-match
if [[ ! $? -eq 0 ]];then
  echo "Nothing to publish, exiting.."
  exit 0;
fi

## Update the realease with the changelog
NEW_VERSION=`cat lerna.json | jq -r '.version'`
CHANGELOG_BODY=`./node_modules/.bin/lerna-changelog --from v$OLD_VERSION --to v$NEW_VERSION`
ESCAPED_CHANGELOG_BODY=`echo "$CHANGELOG_BODY" | jq -R -s -c`
sleep 10
curl -H "Authorization: token $GITHUB_AUTH" --data "{
    \"tag_name\": \"v$NEW_VERSION\",
    \"body\": $ESCAPED_CHANGELOG_BODY,
    \"prerelease\": $PRERELEASE
}" -X POST "https://api.github.com/repos/$GITHUB_ORG/$GITHUB_REPO/releases"

if [[ $(git describe --exact-match 2> /dev/null || :) =~ -alpha ]];
then
  echo "Publishing alpha pacakges to NPM"
  ./node_modules/.bin/lerna publish from-git --ignore-scripts --dist-tag next --yes

  # Make sure to exit script with code 1 if publish failed
  if [[ ! $? -eq 0 ]];then
    exit 1;
  fi
else
  echo "Did not publish alpha packages"
fi

if [[ ! $(git describe --exact-match 2> /dev/null || :) =~ -alpha ]];
then
  echo "Publishing stable pacakges to NPM"
  ./node_modules/.bin/lerna publish from-git --ignore-scripts --yes

  # and update master with this new version
  git checkout master
  git merge stable
  git push origin master

  # Make sure to exit script with code 1 if publish failed
  if [[ ! $? -eq 0 ]];then
    exit 1;
  fi
else
  echo "Did not publish stable packages"
fi
