#!/usr/bin/python

'''
Both of these examples require GNU find for the -print0 option!

Redoing (for indexing, for example) a Maildir folder:
cd ~/Maildir
find $(pwd)/.[A-z]* -type d -print0 | ~/bin/redo-dirs

Redoing most normal directory hierarchies (untested):
cd /the/place/to/redo
find $(pwd)/[A-z]* $(pwd)/.[A-z]* -type d -print0 | ~/bin/redo-dirs
'''

import os
import sys
import stat
import string

temp_extension='.warble.ptang.ptang'

def readline0(file, separator='\0'):
	# this function assumes that there will be a null once in a while.  If you feed it with a huge block of data that has
	# no nulls, woe betide you.
	blocksize = 65536
	buffer = ''
	fields = []
	while 1:
		block = file.read(blocksize)
		if fields[0:]:
			# nth time through loop, n>=2
			if buffer[-1:] == separator:
				# buffer ended in a null byte, so we need to yield a null string, and buffer is the block
				if not block:
#					yield ''
					break
				else:
#					yield ''
					buffer = block
			else:
				# buffer did not end in a null byte, so we have a partial element to return that needs to be saved
				if not block:
					yield fields[-1]
					break
				else:
					buffer = fields[-1] + block
		else:
			# first time through the loop - an empty block is an empty input
			# a nonempty block is something to part out
			if not block:
				break
			else:
				buffer = block
		fields = string.splitfields(buffer, separator)
		for field in fields[:-1]:
			yield field
	raise StopIteration

def bad_dir(dir):
	sys.stderr.write('Sorry, I can only work on directories specified by absolute path that I have access to, error on %s\n' % dir)
	sys.exit(1)

# inhale all of the directories, null terminated
directories = []
for filename in readline0(sys.stdin):
	sys.stderr.write('Got directory %s - saving it for later\n' % filename)
	directories.append(filename)

# make sure all the directories are absolute paths to directories we have access to
for directory in directories:
	os.chdir('/')
	try:
		os.chdir(directory)
	except:
		bad_dir(directory)
	if directory[:1] != '/':
		bad_dir(directory)

sys.stderr.write('Good, all directories read appear to be accessible and specified by absolute path\n')

for directory in directories:
	sys.stderr.write('Working on directory %s\n' % directory)
	os.chdir(directory)
	stat_buf = os.stat(directory)
	perms = stat_buf[stat.ST_MODE] & 0777
	os.rename(directory, directory+temp_extension)
	os.mkdir(directory, perms)
	os.chdir(directory+temp_extension)
	for filename in os.listdir('.'):
		os.rename(filename, '%s/%s' % (directory, filename))
	os.rmdir(directory+temp_extension)