#!/bin/bash

set -e

function usage()
{
cat <<EOF
Usage $0 <option> module
where options are:
 * -p: print package
 * -o: print only package (implies -p)
EOF
}

if ! ARGS=`getopt "hpo" "$@"`; then
	usage
fi
MODULE=`echo $ARGS|sed -e 's/.* *-- *//'`
ARGS=`echo $ARGS|sed -e 's/ *--.*//'`
PACKAGE=0
PACKAGEONLY=0
if echo $ARGS | grep '\-h' >/dev/null; then
	usage
	exit 1
fi
if echo $ARGS | grep '\-p' >/dev/null; then
	PACKAGE=1
else
	PACKAGE=0
fi
if echo $ARGS | grep '\-o' >/dev/null; then
	PACKAGE=1
	PACKAGEONLY=1
else
	PACKAGEONLY=0
fi

NFILE=""
for d in /usr/share/nodejs /usr/lib/nodejs /usr/lib/*/nodejs; do
	if test -d $d; then
		NFILE="$NFILE $d"
	fi
done
FILE=`node -e "console.log(require.resolve('$MODULE'))"|perl -pe 's/(nodejs\/[^\/]*)(\/.*)?$/$1/'`
if test "$PACKAGE" = "1"; then
	if test $PACKAGEONLY = 1; then
		dpkg -S $FILE|sed -e 's/:.*//'
	else
		dpkg -S $FILE
	fi
else
	echo $FILE
fi
