#!/usr/bin/env bash

set -o pipefail
set -o errexit
set -o nounset

# Set magic variables for current file & dir
__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
__file="${__dir}/$(basename "${BASH_SOURCE[0]}")"
__base="$(basename ${__file} .sh)"
__root="$(cd "$(dirname "${__dir}")" && pwd)"

is_local="${LOCAL:-0}"
echo "Local release: $is_local"

if [[ ! "$@" =~ -y ]]; then
  echo "Make sure to read https://uppy.io/docs/contributing#Releases!"
  echo "Press Enter when ready, or Ctrl+C if you still need to do something."
  echo "Use 'npm run release -- -y' to bypass this message."
  read
fi

if [ $is_local == "0" ] && [[ ! "$(npm get registry)" =~ https://registry\.npmjs\.(com|org)/? ]]; then
  echo "Found unexpected npm registry: $(npm get registry)"
  echo "Run this to fix:"
  echo ""
  echo "npm set registry https://registry.npmjs.org"
  exit 1
fi

if ! npm whoami > /dev/null; then
  echo "Not authenticated with npm. First do:"
  echo ""
  echo "npm login"
  exit 1
fi

set -o xtrace

# Update README before publishing `uppy`
# So up-to-date contributors are shown on the npm page.
npm run contributors:save
git add README.md

# Add readme file to the main `uppy` package.
cp README.md packages/uppy/README.md

npm run build:clean
FRESH=1 npm run build

echo "!! The next step is the actual release!"
echo "!! If something goes wrong after here, it becomes hard to reverse. Please make sure that everything is in order."
echo "Press Enter when ready, or Ctrl+C if you still need to do something."
read

git commit --allow-empty -m "Release"
lerna version --amend --no-push --exact

lerna publish from-git

if [ $is_local == "0" ]; then
  git push
  git push --tags
fi
