#!/dcs/bin/python

import sys
import posix
import posixpath
import string
import stat

# input is n lines for n uids to change.
# each line has "olduid newuid" no quotes, whitespace separated
# files are done "from here down"

def get0():
    s = ''
    while 1:
        ch = sys.stdin.read(1)
        if not ch or ch == chr(0):
            break
        s = s + ch
    return s
    
def traverse(uidmap,file='.',device=-1,priorpath=''):
    s = posix.lstat(file)
    if device == -1:
        # memorize the device
        device = s[stat.ST_DEV]
    if stat.S_ISLNK(s[stat.ST_MODE]):
        sys.stdout.write(priorpath+file+' ==> Symbolic Link\n')
        return
    if stat.S_ISDIR(s[stat.ST_MODE]):
        # if not in the same device, stop descending
        if device <> s[stat.ST_DEV]:
            sys.stdout.write(priorpath+file+' ==> Different Device\n')
            return
        # recurse
        posix.chdir(file)
        for filename in posix.listdir('.'):
            if filename <> '.' and filename <> '..':
                traverse(uidmap,filename,device,priorpath+file+'/')
        if file <> '.':
            # only backup a level, if we actually descended a level previously!
            # otherwise, we chmod something a level too high in the tree...
            posix.chdir('..')
    sys.stdout.write(priorpath+file)
    # sys.stdout.write(str(s[stat.ST_UID])+' ')
    if uidmap.has_key(s[stat.ST_UID]):
        posix.chown(file,uidmap[s[stat.ST_UID]],s[stat.ST_GID])
        sys.stdout.write(' '+str(s[stat.ST_UID])+ \
            ' --> '+str(uidmap[s[stat.ST_UID]]))
    sys.stdout.write('\n')

def main():
    if sys.argv[1:] and sys.argv[1] == '-h':
        sys.stderr.write('To use:\n')
        sys.stderr.write('\tFeed me one line per user to chown.\n')
        sys.stderr.write('\tThe line should be of the form "olduid newuid".\n')
        sys.stderr.write('\tYou can easily get this information by seding\n')
        sys.stderr.write('\tuid-merge output.\n')
        sys.exit(0)
    uidmap = {}
    while 1:
        line = sys.stdin.readline()
        if not line:
            break
        oldnew = string.split(line)
        uidmap[string.atoi(oldnew[0])] = string.atoi(oldnew[1])
    traverse(uidmap,'.')

if __name__ == '__main__': main()
#main()