#
#f1 = open('OldNames.lst')
#f2 = open('NewNames.lst')
#f3 = open('rename.sh', 'w')
#
#list1 = f1.readlines()
#list2 = f2.readlines()
#
#for i in range(len(list1)):
#    fr = list1[i].strip()
#    to = list2[i].strip()
#    if fr != to:
#        print >> f3, '%-50s %s' % (fr, to)
#    
#
#f1.close()
#f2.close()
#f3.close()

import os, sys, commands
lst = open('rename.now').readlines()
words = [x.strip().split() for x in lst]

exclude = ['boost', 'po', 'lib/images', 'rename.sh', 'OLD-CHANGES' ]
exclude_types = ['xpm', 'ttf', 'png', 'gz', 'jpg', 'pdf']

def getAllSVNfiles():
    ' get all files in svn'
    filelist = []
    for file in commands.getoutput('svn status -v').split('\n'):
        if file[0] == '?':
            continue
        else:
            name = file.split()[-1]
            # exclude directory
            valid = 'ChangeLog' not in name \
                and os.path.isfile(name) \
                and name.split('.')[-1] not in exclude_types
            for ex in exclude:
                # start with boost etc
                if ex in name and name[:len(ex)] == ex:
                    valid = False
                    break
            if valid:
                filelist.append(name)
    return filelist
        
    
def processFile():
    for fname in getAllSVNfiles():
        if not os.path.isfile(fname):
            continue
        print "Processing", fname
        cmd = "perl -pi.bak "
        frname = fname.split('/')[-1]
        toname = [x[1] for x in words if os.path.normpath(x[0]) == os.path.normpath(fname)]
        # for _moc include
        if len(toname) == 1 and toname[0][-4:] == '.cpp':
            cmd += r" -e 's/%s/%s/g;' " % (frname.replace('.C', '_moc.cpp'), 
                toname[0].split('/')[-1].replace('.cpp', '_moc.cpp'))
        # for #ifdef _XXX_H
        if len(toname) == 1 and toname[0][-2:] == '.h':
            cmd += r" -e 's/%s/%s/g;' " % (frname.upper().replace('.', '_'), 
                toname[0].split('/')[-1].upper().replace('.', '_'))
        # for filenames 
        for ch in words:
            fr = ch[0].split('/')[-1]
            to = ch[1].split('/')[-1]
            fr = fr.replace('.', '\\.')
            to = to.replace('.', '\\.')
            cmd += r"-e 's/(\W|^)%s(\W|$)/\1%s\2/g;' " % (fr, to)
        #print cmd + fname
        os.system(cmd + fname)


def renameFile():
    for ch in words:
        # maybe derived file
        if not os.path.isfile(ch[0]):
            continue
        # file in the way
        if os.path.isfile(ch[1]):
            os.remove(ch[1])
        print 'Renaming %s to %s...' % (ch[0], ch[1])
        os.system("svn rename --force %s %s" % (ch[0], ch[1]))


if __name__ == '__main__':
    if 'step1' == sys.argv[1]:
        processFile()
    if 'step2' == sys.argv[1]:
        renameFile()

