#!/bin/bash

set -e

function usage()
{
cat <<EOF
Usage: pkgjs-audit <module>

pkgjs-audit builds a temporary package-lock.json file using devDependencies
and launches a "npm audit" with it. This permits one to check vulnerabilities
in case of bundled package.

If <module> is given, pkgjs-audit uses installed module, else it launch audit
using current directory.

Copyright (C) 2022 Xavier Guimard <yadd@debian.org>

Licensed under GPL-2+ (see /usr/share/common-licenses/GPL-2)
EOF
}
function version()
{
echo `perl -MDebian::PkgJs::Version -e 'print $VERSION'`
}

if test "$1" = "--version"; then
	version
	exit
fi
while getopts 'vh' opt; do
	case $opt in
		h)
			usage
			exit
			;;
		v)
			version
			exit
			;;
		*)
			echo "Unknown option $opt" >&2
			exit 1
			;;
	esac
done

PKG="$1"

DIR=`mktemp -d`
if test "$PKG" != ""; then
	NPATH=`nodepath $PKG || true`
	if test "$NPATH" = ""; then
		echo "$PKG not found" >&2
		exit 1
	fi
else
	if test -e package.json -o -e package.yaml; then
		NPATH='.'
	else
		echo "Not in a module directory" >&2
		exit 1
	fi
fi
if test -e "$NPATH/pkgjs-lock.json"; then
	cp "$NPATH/pkgjs-lock.json" "$DIR/package-lock.json"
	cp "$NPATH"/package.* "$DIR/"
else
	echo "No pkgjs-lock found, generate it"
	cp "$NPATH"/package.* "$DIR/"
	(cd "$DIR"; perl -MDebian::PkgJs::PackageLock -e 'buildPackageLock(".","package-lock.json")')
fi
(cd $DIR; npm audit)
rm -rf "$DIR"
exit
