#! /usr/bin/env python
# $Id: dpns-find,v 1.1 2008/10/21 09:02:26 gcowan Exp $

__author__ = 'Greig A Cowan'
__date__ = 'October 2008'
__version = 0.1

'''find like utility for DPM namespace.'''

import sys

try:
    import dpm
except:
    print 'Failed to import dpm API. Check your $PYTHONPATH. If this is correct, Please check the bitness of your system libraries - it may be that you have 64bit python and 32bit DPM.'
    sys.exit(1)

import stat
from optparse import OptionParser

def main():
    parser = OptionParser(
        usage = 'usage: %prog /dpm/path/to/directory filename')
    parser.add_option('-x','--exclude',dest='exclude',
                      help='Directory to ignore.')
    parser.add_option('-s','--string2prepend',dest='prepend', default='',
		      help='String to prepend to each output dir.')
    parser.add_option('-p','--postpone',dest='postpone', action='store_true', default=False,
		      help='Print out all directories on the same line.')

    (options, args) = parser.parse_args()

    try:
        directory, filename = args[0], args[1]
    except:
        parser.print_help()

    if len(args) > 2:
        parser.error("incorrect number of arguments")

    scan( directory, filename, options.exclude, options.postpone, options.prepend)

def scan( directory, filename, exclude, postpone, prepend):
    '''Scan through the directory tree.'''
    if directory == exclude:
        return 0
    if directory[-1] != '/':
        directory = directory + '/'
    dir_handle = dpm.dpns_opendirg( directory,'')
    if (dir_handle == None) or (dir_handle == 0):
        err_num = dpm.cvar.serrno
        err_string = dpm.sstrerror( err_num)
        print 'Error while looking for ' + name + ': Error ' \
              + str(err_num) + ' (' + err_string + ')'
        sys.exit(1)

    while 1:
        read_pt = dpm.dpns_readdirxr( dir_handle,'')
        if ( read_pt == None) or ( read_pt == 0):
            break
        entry, list = read_pt
        if stat.S_ISREG( entry.filemode):
            if entry.d_name == filename:
		if postpone:
	                print prepend + directory + entry.d_name,
		else:
			print prepend + directory + entry.d_name
        if stat.S_ISDIR( entry.filemode):
            dir = directory + entry.d_name
            scan( dir, filename, exclude, postpone, prepend)
        
    dpm.dpns_closedir( dir_handle)

if __name__ == '__main__':
         main()
