#!/bin/bash

TARGET=$1

function usage() {
	cat <<EOT
Usage: pkgjs-run <target>

Launch script defined in "package.json -> scripts -> <target>" using sh like
a "npm run".

Features:
 - add node_modules/.bin in PATH
 - ignore git, husky, sudo and su commands
EOT
}

if test "$TARGET" = ""; then
	usage
	exit 1
fi
if test "$1" = "--help" || test "$1" = "-h"; then
	usage
	exit
fi
if test "$1" = "--version"; then
    perl -MDebian::PkgJs::Version -le 'print $VERSION'
    exit
fi

COMMAND=`pkgjs-pjson . scripts $TARGET`
if test "$COMMAND" = ""; then
	echo "Target $TARGET is not defined in package.json" >&2
	exit 1
fi

# Fake git / husky
BADCOMMANDS="git husky su sudo"
for command in $BADCOMMANDS; do
	rm -f node_modules/.bin/$command
	ln -s /usr/bin/true node_modules/.bin/$command
done

# Main: launch wanted command
export PATH="node_modules/.bin:$PATH"
CODE=0
sh -c "$COMMAND" || CODE=$?

# Clean our stuff
for command in $BADCOMMANDS; do
	rm -f node_modules/.bin/$command
done
rmdir node_modules/.bin 2>&1 || true
rmdir node_modules 2>&1 || true
exit $CODE
