#!/usr/bin/env bash
# Regression test for cleanup, npm-to-pnpm migration, release age, dry-run, and automation.

set -Eeuo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
RUNNER="$SCRIPT_DIR/dep-upgrader.sh"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
WS="$TMP/workspace"
BIN="$TMP/bin"
mkdir -p "$WS/apps/web/.next" "$WS/apps/web/node_modules" "$WS/node_modules" "$BIN"
printf x >"$WS/apps/web/.next/cache"
printf x >"$WS/apps/web/node_modules/file"
printf x >"$WS/node_modules/file"

cat >"$WS/package.json" <<'JSON'
{"name":"fixture-root","private":true,"workspaces":["apps/*"],"devDependencies":{"typescript":"^5.0.0"}}
JSON
cat >"$WS/apps/web/package.json" <<'JSON'
{"name":"fixture-web","private":true,"dependencies":{"next":"14.0.0","react":"18.0.0"}}
JSON
printf '{"name":"fixture-root","lockfileVersion":3,"packages":{}}\n' >"$WS/package-lock.json"
printf '{"name":"fixture-web","lockfileVersion":3,"packages":{}}\n' >"$WS/apps/web/package-lock.json"

cat >"$BIN/pnpm" <<'STUB'
#!/usr/bin/env bash
printf '%q ' "$@" >>"$PNPM_LOG"
printf '\n' >>"$PNPM_LOG"
if [[ "${1:-}" == --version ]]; then echo 10.12.0; exit 0; fi
if [[ "${1:-}" == audit && "${2:-}" == --help ]]; then echo signatures; exit 0; fi
exit 0
STUB
chmod +x "$BIN/pnpm"

for file in "$RUNNER" "$SCRIPT_DIR"/lib/*.sh; do bash -n "$file"; done

PNPM_LOG="$TMP/pnpm.log" PATH="$BIN:$PATH" "$RUNNER" \
  --root "$WS" --non-interactive --module deps --ecosystems node \
  --mode latest --audit report --yes >/dev/null

[[ ! -e "$WS/node_modules" ]]
[[ ! -e "$WS/apps/web/node_modules" ]]
[[ ! -e "$WS/apps/web/.next" ]]
[[ ! -e "$WS/package-lock.json" ]]
[[ ! -e "$WS/apps/web/package-lock.json" ]]
grep -q '"packageManager": "pnpm@10.12.0"' "$WS/package.json"
grep -q '"packageManager": "pnpm@10.12.0"' "$WS/apps/web/package.json"
grep -q '^minimumReleaseAge: 10080$' "$WS/pnpm-workspace.yaml"
grep -q 'dlx npm-check-updates@latest -u --target latest' "$TMP/pnpm.log"
if grep -Eq '(^| )(-r|--recursive)( |$).*dlx' "$TMP/pnpm.log"; then
  printf 'Recursive pnpm dlx invocation detected.\n' >&2
  exit 1
fi

archive="$(find "$WS/.maintenance/backups" -name '*.tar.gz' -print -quit)"
tar -tzf "$archive" | grep -q '^./package.json$'

mkdir -p "$WS/node_modules" "$WS/apps/web/.next"
touch "$WS/node_modules/keep" "$WS/apps/web/.next/keep"
before="$(cksum "$WS/package.json")"
PNPM_LOG="$TMP/pnpm-dry.log" PATH="$BIN:$PATH" "$RUNNER" \
  --root "$WS" --non-interactive --module deps --ecosystems node \
  --mode latest --dry-run >/dev/null
[[ -e "$WS/node_modules/keep" ]]
[[ -e "$WS/apps/web/.next/keep" ]]
[[ "$before" == "$(cksum "$WS/package.json")" ]]

PNPM_LOG="$TMP/pnpm-automation.log" PATH="$BIN:$PATH" "$RUNNER" \
  --root "$WS" --non-interactive --module automation --yes >/dev/null
node -e 'const r=require(process.argv[1]);if(r.minimumReleaseAge!=="7 days")process.exit(1)' "$WS/renovate.json"
[[ -f "$WS/.changeset/config.json" ]]

printf 'dep-upgrader smoke test passed\n'
