#!/bin/sh

basedir=$(dirname "$0")

<%_ if (buildToolMaven) { _%>
if [ -f "$basedir/mvnw" ]; then
  bindir="$basedir/target/node"
  repodir="$basedir/target/node/node_modules"
  installCommand="$basedir/mvnw --batch-mode -ntp -Pwebapp frontend:install-node-and-pnpm@install-node-and-pnpm"
<%_ } else if (buildToolGradle) { _%>
if [ -f "$basedir/gradlew" ]; then
  bindir="$basedir/build/node/bin"
  repodir="$basedir/build/node/lib/node_modules"
  installCommand="$basedir/gradlew npmSetup --no-daemon"
<%_ } _%>
else
  echo "Using pnpm installed globally"
  exec pnpm "$@"
fi
PNPM_EXE="$repodir/pnpm/bin/pnpm.cjs"
NODE_EXE="$bindir/node"

if [ ! -x "$PNPM_EXE" ] || [ ! -x "$NODE_EXE" ]; then
  $installCommand || true
fi

if [ -x "$NODE_EXE" ]; then
  echo "Using node installed locally $($NODE_EXE --version)"
  PATH="$bindir:$PATH"
else
  NODE_EXE='node'
fi

if [ ! -x "$PNPM_EXE" ]; then
  echo "Local npm not found, using npm installed globally"
  pnpm "$@"
else
  echo "Using pnpm installed locally $($NODE_EXE $PNPM_EXE --version)"
  $NODE_EXE $PNPM_EXE "$@"
fi
