#!/usr/bin/python2.4

import sys
import os

def printUsage():
    print 'Usage: backupPhotos dirname oldDirname'

def listdirlong(dirname):
    """Return a List like os.listdir() but with full qualified path names. ['/home/user/file'] instead of ['file']"""
    return [dirname+'/'+f for f in os.listdir(dirname)]

def rescaleOriginalFiles(dirname, archieved_files):
    files_to_process = listdirlong(dirname)
    
    while len(files_to_process) != 0:
        f = files_to_process.pop()
        
        if os.path.isdir(f):
            files_to_process.extend(listdirlong(f))
        elif os.path.isfile(f):
            imagename = f.rsplit('/', 1)[1]
            if filelistcontains(archieved_files, imagename):
                rescale(f)
                print 'rescaled ', f

def filelistcontains(list1, item):
    """Check if a filename is contained in list1. P.E. filelistcontains(['/home/user/file'], 'file') == True"""
    try:
        [f.rsplit('/', 1)[1] for f in list1].index(item)
        return True
    except:
        return False

def rescale(imagefile):
    """Handle rescaling of an imagefile"""
    os.system('mogrify -scale 150 '+imagefile)

if __name__ == '__main__':
    actDir = os.getcwd()
    
    if(len(sys.argv) < 3):
        printUsage()
    else:
        print sys.argv
        archieved = listdirlong(sys.argv[1])
        print 'found images ', ', '.join(archieved)
        print 'now rescaling...'
        rescaleOriginalFiles(sys.argv[2], archieved)
