#!/usr/bin/env bash
set -e

YELLOW='\033[0;33m'
CYAN='\033[0;36m'
RESET='\033[0m' # No Color

PACKAGE_NAME="mx-web"
SCRIPTS_FORDER_NAME="scripts"


PWD=$(pwd)
if [[ ${PWD:(-7)} != "/$PACKAGE_NAME" ]]; then
  echo "Please run this script in the package root directory."
  exit 0;
fi

echo -e "${YELLOW}[Publishing] ${CYAN}Step (0): Check if your NPM_TOKEN has the 'publish' permission${RESET}"

if [[ ${#NPM_TOKEN} == 0 ]]; then
  echo "You need to have a NPM_TOKEN token under wework-dev team account."
  exit 0;
fi

cd "./$SCRIPTS_FORDER_NAME"
VERSION=$(npm view mx-web-publish version)
NEXT_VERSION=${VERSION:0:4}$((${VERSION:(-1)} + 1))
npm version $NEXT_VERSION --allow-same-version
npm publish

echo -e "${YELLOW}[Publishing] ${CYAN}Step (1): Change to publish branch${RESET}"
git checkout master
git pull origin master
git checkout publish
git merge --ff-only master

echo -e "${YELLOW}[Publishing] ${CYAN}Step (2): @lerna/changed${RESET}"
PACKAGES=$(lerna changed --include-merged-tags | tr '\n' ',' | sed 's/.$//')

if [ -z $PACKAGES ]; then
  echo "No Packages have changed since the last tagged release."
  exit 0;
fi

if [[ $PACKAGES == *","* ]]; then
  # wraps mulitple packages names
  PACKAGES="{$PACKAGES}"
fi

echo -e "${YELLOW}[Publishing] ${CYAN}Step (3): npm run build${RESET}"
lerna exec --scope=$PACKAGES --concurrency 1 --stream -- 'npm run build'

echo -e "${YELLOW}[Publishing] ${CYAN}Step (4): @lerna/version${RESET}"
lerna version --include-merged-tags --yes

echo -e "${YELLOW}[Publishing] ${CYAN}Step (5): @lerna/publish${RESET}"
lerna publish from-git --ignore-scripts --yes
