#! /usr/bin/env python2.2

# Very simple program that searches the /usr/portage tree for 
# ebuilds that match a key provided by the user.

from os.path import splitext, walk, isdir
import re

portageRoot = "/usr/portage"
installRoot = "/var/db/pkg"

# inelegant routine to assemble the install directory that is associated
# with a given portage directory
def getinstalldir(portagedir):
   path = portagedir.split('/')
   installdir = installRoot
   for dir in path[3:-1]:
      installdir += "/" + dir
   return installdir

# workhorse routine: for each directory look for ebuild files and
# interrogate each ebuild file to see if it matches the key and,
# if it does, also check to see if it is installed.
def visit(key, dirname, files):
   for file in files:
      (base, ext) = splitext(file)
      if (ext == ".ebuild"):
         if (re.search(key.lower(), base.lower())):
            # package found.  Is it also installed?
            installname = getinstalldir(dirname) + '/' + base
            if (isdir(installname)):
               print dirname + "/" + file + "\t (installed)"
            else:
               print dirname + "/" + file


if __name__ == '__main__':
   import sys
   if (len(sys.argv) != 2):
      print "Usage: pkgsearch key"
      sys.exit(1)
   key = sys.argv[1]
   walk(portageRoot, visit, key)

