#!/usr/bin/env bash
# Frozen pnpm install with ephemeral GitHub Packages auth (never mutates repo .npmrc).
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"

if ! command -v pnpm >/dev/null 2>&1; then
  # shellcheck source=setup-pnpm-action.sh
  source "$(dirname "${BASH_SOURCE[0]}")/setup-pnpm-action.sh"
fi

TOKEN="${GITHUB_PACKAGES_TOKEN:-}"
TEMP_NPMRC=""
ORIGINAL_USERCONFIG="${NPM_CONFIG_USERCONFIG:-}"
CLEANUP_RAN=0
CLEANUP_ERRORS=()

report_cleanup_error() {
  CLEANUP_ERRORS+=("$1")
  echo "setup-pnpm-install cleanup: $1" >&2
}

cleanup_once() {
  if (( CLEANUP_RAN )); then
    return 0
  fi
  CLEANUP_RAN=1

  if [[ -n "$TEMP_NPMRC" && -f "$TEMP_NPMRC" ]]; then
    if ! rm -f "$TEMP_NPMRC"; then
      report_cleanup_error "failed to remove ephemeral npmrc"
    fi
  fi
  if [[ -n "$ORIGINAL_USERCONFIG" ]]; then
    export NPM_CONFIG_USERCONFIG="$ORIGINAL_USERCONFIG"
  else
    unset NPM_CONFIG_USERCONFIG
  fi
}

on_exit() {
  local exit_code=$?
  trap - EXIT INT TERM
  cleanup_once
  if (( ${#CLEANUP_ERRORS[@]} > 0 && exit_code == 0 )); then
    exit 1
  fi
  exit "$exit_code"
}

on_int() {
  trap - EXIT INT TERM
  cleanup_once
  exit 130
}

on_term() {
  trap - EXIT INT TERM
  cleanup_once
  exit 143
}

trap on_exit EXIT
trap on_int INT
trap on_term TERM

has_private_deps() {
  if [[ ! -f pnpm-lock.yaml ]]; then
    return 1
  fi
  grep -q '@platform-modules/' pnpm-lock.yaml
}

if has_private_deps && [[ -z "${TOKEN//[[:space:]]/}" ]]; then
  echo 'setup-pnpm-install: GitHub Packages token required for @platform-modules dependencies' >&2
  exit 1
fi

if [[ -n "${TOKEN//[[:space:]]/}" ]]; then
  TEMP_NPMRC="$(mktemp "${TMPDIR:-/tmp}/multideal-npmrc.XXXXXX")"
  chmod 600 "$TEMP_NPMRC"
  umask 077
  {
    printf '%s\n' '@platform-modules:registry=https://npm.pkg.github.com'
    printf '%s\n' "//npm.pkg.github.com/:_authToken=${TOKEN}"
  } >"$TEMP_NPMRC"
  export NPM_CONFIG_USERCONFIG="$TEMP_NPMRC"
fi

pnpm install --frozen-lockfile "$@"
