#!/bin/sh
# Upstream migrated its test suite to vitest, which is not packaged in Debian.
# Exercise the offline part of corepack with the real CLI instead: this is what
# the upstream tests/Enable.test.ts and tests/Disable.test.ts covered. The rest
# of the upstream suite downloads package managers and needs network access.
set -e

DIST=$(node -e 'const p = require("path");
console.log(p.join(p.dirname(require.resolve("corepack/package.json")), "dist"));')
COREPACK="node $DIST/corepack.js"

TMPDIR_TEST=$(mktemp -d)
trap 'rm -rf "$TMPDIR_TEST"' EXIT

fail() {
  echo "FAIL: $1" >&2
  exit 1
}

# --version prints the packaged version
VERSION=$($COREPACK --version)
echo "corepack --version: $VERSION"
echo "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+' \
  || fail "unexpected --version output: $VERSION"

# --help lists the shim management commands
$COREPACK --help > "$TMPDIR_TEST/help.txt" 2>&1 \
  || fail "corepack --help exited non-zero"
grep -q 'corepack enable' "$TMPDIR_TEST/help.txt" \
  || fail "corepack --help does not mention 'enable'"

# enable installs the shims in the requested directory
BIN="$TMPDIR_TEST/bin"
mkdir "$BIN"
$COREPACK enable --install-directory "$BIN" || fail "corepack enable failed"

for shim in yarn yarnpkg pnpm pnpx; do
  test -L "$BIN/$shim" || fail "corepack enable did not create the $shim symlink"
  target=$(cd "$BIN" && readlink -f "$shim")
  test "$target" = "$DIST/$shim.js" \
    || fail "$shim points to $target instead of $DIST/$shim.js"
done

# npm is deliberately not shimmed: it ships with Node
test ! -e "$BIN/npm" || fail "corepack enable should not have created an npm shim"

# enable is idempotent
$COREPACK enable --install-directory "$BIN" || fail "second corepack enable failed"
test -L "$BIN/yarn" || fail "second corepack enable removed the yarn symlink"

# enable accepts an explicit package manager name
BIN2="$TMPDIR_TEST/bin2"
mkdir "$BIN2"
$COREPACK enable --install-directory "$BIN2" yarn || fail "corepack enable yarn failed"
test -L "$BIN2/yarn" || fail "corepack enable yarn did not create the yarn symlink"
test ! -e "$BIN2/pnpm" || fail "corepack enable yarn also created the pnpm shim"

# an unknown package manager is rejected
if $COREPACK enable --install-directory "$BIN2" notapackagemanager > "$TMPDIR_TEST/err.txt" 2>&1; then
  fail "corepack enable accepted an invalid package manager name"
fi

# disable removes the shims again
$COREPACK disable --install-directory "$BIN" || fail "corepack disable failed"
for shim in yarn yarnpkg pnpm pnpx; do
  test ! -e "$BIN/$shim" || fail "corepack disable left the $shim shim behind"
done

echo "All corepack offline tests passed."
