#!/usr/bin/env python
#
#     This script will check all files under the current directory
#     to see if they need to be laundered.  Suspicious files will have
#     the following keywords in them -
#
#	bakken
#	fnal
#	d0
#

import os
import re
import stat
import time
import getopt
import sys

# various files to ignore
ignoreEnds = ["\.pyc$", "\.o$", "\.so$", "\.a$", "\.ps$", "\.gif$", "\.kil$",
	      "\.jou$", "~$", "\.in$"]
ignoreDirs = ["CVS", "WWW_new"]
ignoreFiles = ["laundry", ".cvsignore", "trace_delta", "traceShow", "pending_queue", 
	       "work_at_movers"]
ignoreStarts = ["^LOG-.*", "^__db.*", "^\.#.*", "^dirt.txt.*", "^log.00000000.*"]
ignoreStartsPatterns = []
ignoreEndsPatterns = []

def patternSearch(pats, file):
    # make sure this file does not start with ignoreStarts
    for pat in pats:
	if pat.search(file):
	    break
    else:
	return 0
    return 1

def do_the_walk((dirtFile, dirt), dir, files):
    
    toRemove = []
    for file in files:
	thefile = "%s/%s"%(dir, file)
	# get info on this file
	mode = os.lstat(thefile)[stat.ST_MODE]
	if stat.S_ISDIR(mode):
	    # this is a directory
	    if file in ignoreDirs: 
		# ignore this directory, remove it from the list later
		toRemove.append(file)
	elif stat.S_ISREG(mode):
	    # this is a regular file, make sure it is not one to ignore
	    if patternSearch(ignoreStartsPatterns, file) or \
	       patternSearch(ignoreEndsPatterns, file):
		# this file's end/start labels it as ignorable
		print "%s ignored"%(thefile,)
		continue
	    elif not file == dirtFile and not file in ignoreFiles:
		# check this file for the dirt - open the output file
		df = open(dirtFile, 'a')
		df.write("FILE: %s - \n"%(thefile,))
		df.close()
		for d in dirt:
		    os.system("fgrep -i %s %s >> %s"%(d, thefile, dirtFile))
    else:
	# now remove any unwanted directories from the list of files
	if toRemove:
	    for aDir in toRemove:
		files.remove(aDir)

class Laundry:

    currentDir = "."
    dirtFile = "dirt.txt"
    defaultDirt = ["bakken", "fnal", "d0"]
    #defaultDirt = ["jon", "rip", "131"]
    dirt = defaultDirt


    def __init__(self):
	# process imputs
	try:
	    options = ["dirt="]
	    optlist, args = getopt.getopt(sys.argv[1:], "", options)
	except getopt.error, detail:
	    print "error: ", detail
	    print "Usage: laundry [--dirt=\"[\\\"str1\\\", \\\"str2\\\"...]\""
	    sys.exit(1)
	    
	if not len(optlist) == 0:
	    # we have some input
	    for (opt, value) in optlist:
		if opt == "--dirt":
		    self.dirt = eval(value)

	# write the header to the output file
	df = open(self.dirtFile, 'w')
	df.write("Laundry done on %s at %s\n"%(os.uname()[1], 
					   time.ctime(time.time())))
	df.write("    looking for %s\n\n"%(repr(self.dirt),))
	df.close()

	# compile the patters
	for pat in ignoreStarts:
	    ignoreStartsPatterns.append(re.compile(pat))
	for pat in ignoreEnds:
	    ignoreEndsPatterns.append(re.compile(pat))

    def doLaundry(self):
	# walk the directory to search for files 
	os.path.walk(self.currentDir, do_the_walk, (self.dirtFile, self.dirt))

if __name__ == "__main__" :

    lf = Laundry()
    lf.doLaundry()
