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

if test -n "$(git status --porcelain)"; then
  echo 'Unclean working tree. Commit or stash changes first.' >&2
  exit 128
fi

echo "Select release type"
echo "1. Production"
echo "2. Other"

read TYPE

if [ $TYPE == 1 ]; then
  git checkout master

  VERSION=$(npx select-version-cli)
  read -p "Building $VERSION - are you sure? (y/n)" -n 1 -r
  echo # (optional) move to a new line
  if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "Building $VERSION ..."

    # build
    export NODE_OPTIONS="--max_old_space_size=4096"
    VERSION=$VERSION npm run pro-build
    cp htaccess/.htaccess dist/.htaccess
    # ssr test
    # node test/ssr/require.test.js

    # publishing packages
    echo "Releasing project version $VERSION ..."

    # commit
    git add -A
    git commit -m "[build] $VERSION" --no-verify
    npm version $VERSION --message "build: release build $VERSION"
    git push origin master
    git push origin v$VERSION
  fi
elif [ $TYPE == 2 ]; then
  echo "Enter the branch/version name: "
  read RELEASING_VERSION
  git checkout $RELEASING_VERSION
  read -p "Building $RELEASING_VERSION version - are you sure? (y/n)" -n 1 -r
  echo # (optional) move to a new line
  if [[ $REPLY =~ ^[Yy]$ ]]; then

    # build
    export NODE_OPTIONS="--max_old_space_size=4096"

    npm run build
    cp htaccess/.htaccess dist/.htaccess
    # ssr test
    # node test/ssr/require.test.js

    # publishing packages
    echo "Building project version qa ..."

    # commit
    git add -A
    git commit -m "[qa build]" --no-verify
    git push origin $RELEASING_VERSION
  fi
else
  echo "Invalid selection."
  exit 128
fi
