#!/usr/bin/python
###########
# likefind
# Finds files that are similer to a given file
# URL to Wiki: http://git.toolbox.hostgator.com/likefind/pages/Home
# URL to GIT: http://git.toolbox.hostgator.com/likefind
# Please submit all bug reports at bugs.hostgator.com
#
# (C) 2011 - HostGator.com, LLC
###########


import os
import stat
import fnmatch

st_ino_threshold = 100
st_time_threshold = 60

def filetypecheck(x, y):
	if y & 16384:
		return 0
	elif y & 32768:
		return 1
	return -1

def neg_or_equ(x, y):
    return (x == -1 ) or (x == y)

def neg_or_timethresh(x, y):
    return (x == -1 ) or (-st_time_threshold <= (x-y) <= st_time_threshold)

def neg_or_inodethresh(x, y):
    return (x == -1 ) or (-st_ino_threshold <= (x-y) <= st_ino_threshold)

default_filestat_filter_funcs = (
    filetypecheck,
    neg_or_inodethresh,
    neg_or_equ,
    neg_or_equ,
    neg_or_equ,
    neg_or_equ,
    neg_or_equ,
    neg_or_timethresh, 
    neg_or_timethresh, 
    neg_or_timethresh, 
)

def walkpath(path,
             maxdepth=False,
             filename_glob=False,
             filestat_filter_set=None,
             filestat_filter_funcs=default_filestat_filter_funcs
             ):
    filestat_filter_set = filestat_filter_set or (-1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
    dir_stack = [path]
    dir_stack_pop = dir_stack.pop
    dir_stack_append = dir_stack.append
    
    
    dirs = []
    dirs_append = dirs.append
    files = []
    files_append = files.append
    
    if maxdepth:
        realdepth = path.count('/') + maxdepth
    else:
        realdepth = False
    
    root = dir_stack.pop()
    while True:

        try:
            names = os.listdir(root)
        except:
            continue
        
        for name in names:
            absname = os.path.join(root, name)
            tmp_stat = os.lstat(absname)
            statmap = zip(filestat_filter_set, tmp_stat)
            stat_filter = [(filestat_filter_funcs[i](x, y)) for i, (x, y)  in enumerate(statmap)]
            passed_filter = not False in stat_filter[1:]
            if stat_filter[0] == 1 and passed_filter:
                files.append(name)

            elif stat_filter[0] == 0 and (not realdepth or absname.count('/') < realdepth):
                dirs_append(name)
                dir_stack_append(absname)
        
        if filename_glob:
            files = fnmatch.filter(files, filename_glob)

        yield root, dirs, files
         
        del dirs[:]
        del files[:] 

        if not dir_stack:
            break

        root = dir_stack_pop()
            
            
if __name__ == "__main__":
    from optparse import OptionParser

    oparser = OptionParser()

    oparser.add_option('--name', dest='name', default='*',
                       help='Only show files that match this glob.')
    oparser.add_option('--maxdepth', dest='maxdepth', default=-1, type=int,
                       help='Maximum search depth.')
    oparser.add_option('--near-inodes', dest='near_inodes',
                       action='store_true', default=False, 
                       help='Show files that have inode numbers close to file.')
    oparser.add_option('--inode-threshold', dest='inode_threshold', 
                       default=100, type=int,
                        help='Threshold for --near-inodes.')
    oparser.add_option('--same-owner', dest='same_owner',
                       action='store_true', default=False, 
                       help='Only show files owned by the same user.')
    oparser.add_option('--same-group', dest='same_group',
                       action='store_true', default=False, 
                       help='Only show files owned by the same group.')
    oparser.add_option('--near-atime', dest='near_atime',
                       action='store_true', default=False, 
                       help='Only show files where the ACCESS time is close to file.')
    oparser.add_option('--near-mtime', dest='near_mtime',
                       action='store_true', default=False, 
                       help='Only show files where the MODIFY time is close to file.')
    oparser.add_option('--near-ctime', dest='near_ctime',
                       action='store_true', default=False, 
                       help='Only show files where the CHANGE time is close to file.')
    oparser.add_option('--time-threshold', dest='time_threshold', 
                       default=60, type=int,
                        help='Threshold for time filtering options.')
                         
    
    (options, args) = oparser.parse_args()

    if len(args) == 1:
        fstat = os.lstat(args[0])
        path = './'
    elif len(args) == 2:
        fstat = os.lstat(args[1])
        path = args[0]
    else:
        print "Usage: prog [options] [<path>] <filename>"
        exit(1)

    if options.near_inodes:
        inode_num = fstat.st_ino
        st_ino_threshold = options.inode_threshold
    else:
        inode_num = -1
    if options.same_owner:
        owner = fstat.st_uid
    else:
        owner = -1
    if options.same_group:
        group = fstat.st_gid
    else:
        group = -1
    if options.near_atime:
        atime = fstat.st_atime
    else:
        atime = -1
    if options.near_mtime:
        mtime = fstat.st_mtime
    else:
        mtime = -1
    if options.near_ctime:
        ctime = fstat.st_ctime
    else:
        ctime = -1

    if atime + mtime + ctime != -3:
        st_time_threshold = options.time_threshold

    for root, dirs, files in walkpath(path, 
                                      maxdepth=options.maxdepth, 
                                      filename_glob=options.name, 
                                      filestat_filter_set=(-1, inode_num, -1, -1, owner, group, -1, atime, mtime, ctime)):
        for f in files:
            print os.path.join(root, f)
