#!/usr/bin/env bash

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

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

VERDACCIO_REGISTRY=http://localhost:4002
CURRENT_COMMIT="$(git rev-parse HEAD)"

cleanup() {
  rm -rf "${__root}/test/endtoend/node_modules"
  rm -rf "${__root}/test/endtoend/tmp"
  git reset
  git checkout $CURRENT_COMMIT
}
function on_exit() {
  # revert to public registry
  npm set registry https://registry.npmjs.org
  cleanup
}
trap on_exit EXIT

echo "Preparing for end to end test: copying static HTML and CSS, building JS"
rm -rf "${__root}/test/endtoend/node_modules"

# list of @uppy/* packages
PACKAGES="$(for pkg in packages/@uppy/*; do echo "${pkg#packages/}"; done)"

cleanup
# Initialise verdaccio storage path.
mkdir -p "${__root}/test/endtoend/tmp/verdaccio"

npm run build

# https://github.com/facebook/create-react-app/pull/4626
(cd && npm-auth-to-token -u user -p password -e user@example.com -r "$VERDACCIO_REGISTRY")

git checkout -b endtoend-test-build
# HACK this thing changes all the time for some reason on CI
# so I'll just ignore it…
git checkout -- package-lock.json

# Simulate a publish of everything, to the local registry,
# without changing things in git
ENDTOEND=1 lerna version prerelease --yes \
  --exact \
  --force-publish \
  --npm-client=npm \
  --no-push
ENDTOEND=1 lerna publish from-git --yes \
  --registry="$VERDACCIO_REGISTRY" \
  --no-verify-access \
  --npm-client=npm

# install all packages to the endtoend folder
# (Don't use the npm cache, don't generate a package-lock, don't save dependencies to any package.json)
pushd "${__root}/test/endtoend"
  npm install \
    --prefer-online \
    --registry "$VERDACCIO_REGISTRY" \
    --no-package-lock \
    --no-save \
    uppy $PACKAGES
popd

bash "${__dir}/endtoend-build-tests"

cleanup
