#!/bin/bash
set -eu
# Download old tests and run them. Written in bash, just because. Needs to do contortions, see below.
#
# Usage:
#
#   download-and-run-old-tests <version> [...args to run-suite...]
set -x

scriptdir=$(cd $(dirname $0) && pwd)

version="$1"
target_directory="old_tests"
shift

rm -rf $target_directory && mkdir $target_directory

# The old tests package MUST be 'npm install <pkg>'ed as a dependency, but MUST NOT
# end up in a `node_modules` directory.
#
# - MUST be 'npm install'ed: we need transitive dependencies as well.
# - as a dependency: if we check out the source and do an `npm install --production` in the
#   package.json directory, NPM will still try to resolve devDependencies (even though it doesn't
#   need to install them), and the devDeps do not exist on npmjs.
# - MUST NOT end up in `node_modules`: Jest 27 will ignore all tests that have `node_modules` in
#   the path, and this behavior is not configurable before Jest 28. Unfortunately, because of TypeScript
#   typing issues, we cannot move past Jest 27.
#
# To achieve this, do an `npm install <pkg>` then follow up with an `mv` to move the files out.
if !  npm install --prefix $target_directory --no-save @aws-cdk-testing/cli-integ@$version > npm.log 2>&1; then
    cat npm.log >&2
    # Catch a "package does not exist" error, have to do it this way because for some reason,
    # 'npm view <pkg>' doesn't exit with an error... :s
    if grep -q 'code ETARGET' npm.log; then
        echo "During migration, @aws-cdk-testing/cli-integ@$version does not exist yet." >&2


        # Do create an empty junit.xml file -- if we don't, then the "upload report" phase will fail
        # if there are 0 files to upload.
        echo '<testsuites id="Norun" name="No run" tests="0" failures="0" time="0"></testsuites>' > junit.xml
        exit 0
    fi
    exit 1
fi

mv $($target_directory/node_modules/.bin/test-root)/* $target_directory

# Apply new patches to old tests
${scriptdir}/apply-patches $version $target_directory

# Run the suite from the old tests
exec $target_directory/bin/run-suite "$@"