#!/usr/bin/env bash

# Called by the `version` npm script.
# This is run _after_ lerna updates the version numbers,
# but _before_ it commits, so we have time to update the
# version numbers throughout the repo and add it to the
# release commit.
# NOTE this _amends_ the previous commit, which should
# already be a "Release" commit generated by bin/release.

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)"

if [ "${ENDTOEND:=0}" = "1" ]; then
  echo "Publishing for e2e tests, skipping version number sync."
  exit 0
fi

commit_message="$(git log -1 --pretty=%B)"
if [ "$commit_message" != "Release" ]; then
  echo "Last commit is not a release commit, but '$commit_message'"
  exit 1
fi

version_files="./examples/ README.md bin/upload-to-cdn.sh website/src/examples/ website/src/docs/ website/themes/uppy/layout/"
main_package_version=$(node -p "require('./packages/uppy/package.json').version")
# Legacy defeater for also renaming the old /dist/ locations, can be removed as soon as everything's on the new dist-less thing
replace-x -r 'uppy/v\d+\.\d+\.\d+/dist/' "uppy/v$main_package_version/" $version_files --exclude=node_modules
replace-x -r 'uppy/v\d+\.\d+\.\d+/' "uppy/v$main_package_version/" $version_files --exclude=node_modules
git add $version_files # add changes to the Release commit
