#!/bin/sh

#  Copyright (C) 2007 Piotr Ożarowski <piotr@debian.org>
#
#  This  program is  free software;  you can  redistribute  it and/or
#  modify it  under the  terms of the  GNU General Public  License as
#  published by the Free Software Foundation; either version 2 of the
#  License, or any later version.
#
#  This program  is distributed in the  hope that it  will be useful,
#  but  WITHOUT ANY WARRANTY;  without even  the implied  warranty of
#  MERCHANTABILITY or  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#  General Public License for more details.

#
# PLEASE NOTE that this script will detect *installed* dependencies only
#
# TODO:
# * detect docstrings

log_fatal() {
    echo "$*" >&2
    exit 1
}

if [ -z "$1" ]
then
	log_fatal "Please specify python module dir/file"
	exit 1
fi

PYTHONPATH=$1
REGEXPR="[a-zA-Z_0-9\.]+"

if [ -x /usr/bin/dlocate ]; then
	FIND="dlocate -S"
else
	FIND="dpkg -S"
fi

# omit "from .* import .*" for now:
MODULES1=`grep -v \# -r $1 | sed -rne "s,.*:\s*import\s+($REGEXPR)\s*,\1,p" | sort -u`

# "from .* import .*"
MODULES2=`grep -v \# -r $1 | sed -rne "s,.*from\s+($REGEXPR)\s+import.*,\1,p" | sort -u`
MODULES=`echo "$MODULES1"; echo "$MODULES2" | sort -u`

# example __file__ output: (remember while grepping)
# * pycentral:
#   runtime: /usr/lib/python2.4/site-packages/chardet/__init__.pyc
#   package: /usr/share/pycentral/python-chardet/site-packages/chardet/__init__.py
# * pysupport:
#   runtime: /var/lib/python-support/python2.4/gtk-2.0/gtk/__init__.pyc
#   package: /usr/share/python-support/python-gtk2/gtk-2.0/gtk/__init__.py
for i in $MODULES; do
	case $i in
		test*|os|os\.*|re|sys|logging|thread|sets|gettext) continue;;
		an|and|the|error*) continue;;
	esac
	#echo "  $i" # DEBUG
	python -c "import $i as tmp; print tmp.__file__" 2>&1 \
		| egrep -v "/usr/lib/python[2-9]\.[0-9]/$REGEXPR.py" \
		| grep -v "Traceback" \
		| grep -v 'File "<string>", line' \
		| grep -v "ImportError: No module named" \
		| grep -v "AttributeError:" \
		| grep -v "/usr/lib/python[0-9].[0-9]/lib-dynload/" \
		| sed -e "s/\.pyc$/.py/" \
			-e "s:.*/site-packages/:site-packages/:" \
			-e "s:.*/python-support/python[0-9]\.[0-9]/::" \
		| xargs -I{} $FIND {}
done
