#!/usr/bin/env python
"""Like `apt-file find`, but for python modules."""

import sys
import os

def readlinks(path):
    """Resolve a symlink to a non-symlink file recursively"""
    try:
        return readlinks(os.path.normpath(os.path.join(os.path.dirname(path), os.readlink(path))))
    except OSError:
        return path

def aptmodfile(modulename, quiet=False):
    module = __import__(modulename)
    module = sys.modules[modulename] # required at least for enthought.traits.api
    modfile = readlinks(module.__file__.rstrip('c'))
    if not quiet:
        print "Module file is %s."%modfile
    if not os.path.exists(modfile):
        print "Warning: %s does not exist on this system."%modfile >> sys.stderr
    os.execvp('apt-file', ['apt-file', 'find', modfile])

if __name__ == "__main__":
    import optparse
    p = optparse.OptionParser(usage="%prog [options] module", description="`apt-file find` a python module")
    p.add_option('-q', '--quiet', help="Supress output of file name, only report module", action='store_true')
    opts, args = p.parse_args()
    if len(args) != 1:
        p.error("incorrect number of arguments")
    aptmodfile(args[0], quiet=opts.quiet)
