#!/usr/bin/python

import sys
import os
import tempfile
import subprocess
import time
    
########################################
#### Subroutines #######################
########################################


# function which sets the finder label for OS X files
def finderLabelFiles(files, labelNum):
    # Write the list of files to label to a temp file
    (tmpFH, tmpPath) = tempfile.mkstemp('.txt')
    os.write(tmpFH, "\n".join(files))
    os.close(tmpFH)
    
    # Open a pipe to and from the applescript interpreter
    asInterpreter = subprocess.Popen(
        "/usr/bin/osascript",
        shell=True,
        stdin=subprocess.PIPE,
        stdout=sys.stdout)
    
    # The script we'll send it
    script = [
        'tell application "Finder"',
        'set fileList to (POSIX file "%s")' % (tmpPath),
        'set labelColor to %i' % (labelNum),
        'try',
        'set fh to open for access fileList',
        'repeat with thisFile in (read fh using delimiter (ASCII character 10))',
        'set label index of item (thisFile as POSIX file) to labelColor',
        'end repeat',
        'close access fh',
        'on error',
        'try',
        'close access fh',
        'end try',
        'end try',
        'end tell'
    ]
    
    asInterpreter.stdin.write("\n".join(script))
    asInterpreter.stdin.close()
    asInterpreter.wait()
    os.unlink(tmpPath)


########################################
#### Main ##############################
########################################

# Sanity-Check Arguments
if (not (len(sys.argv) > 1 and map(os.path.isdir, sys.argv[1:]).count(False) < 1)):
    print "Usage: %s directory_to_search [...]" % (sys.argv[0])
    exit()

# For each directory specified on the command line
for searchDirectory in sys.argv[1:]:
    # Init
    badItems = []
    reportFile = os.path.join(searchDirectory, "Bad Files Report.txt")

    # Main Loop: os.walk returns this tuple for each subdir
    for thisPath, thisPathDirs, thisPathFiles in os.walk(searchDirectory):
        # The parent folder of '/some/path/on/your/computer" is "computer"
        parentFolder = os.path.split(thisPath)[1]
        
        # Does this directory have any files?
        for thisFile in thisPathFiles:
            # Ignore files beginning with a dot
            if thisFile[0:1] == '.': continue
            
            # The base name of "123.jpg" is "123"
            thisFileBaseName = os.path.splitext(thisFile)[0]
            
            # Do the comparison
            if parentFolder != thisFileBaseName:
                badItems.append(os.path.join(thisPath, thisFile))
                badItems.append(thisPath)

    
    # Were there actually were any bad files?
    if len(badItems) > 0:
        badItems = list(set(badItems))
        badItems.sort()
        
        # Write our report
        try:
            report = open(reportFile, 'w')
            report.write("# Bad files in %s on %s:\n" % ( searchDirectory, time.asctime() ) )
            report.write("\n".join(badItems))
            report.close()
        except:
            print "Couldn't write report for %s (%s)" % (searchDirectory, reportFile)
            raise
    
        # Set the finder labels for the empty dirs
        finderLabelFiles(badItems, 2)
    else:
        print 'No bad files were found in "%s"' % (searchDirectory)

exit()
