#!/usr/bin/env python2
"""
    lower - recursively rename directorires to be lowercase
"""

import os
import sys

def rerename(directory):
    try:
        dirs = os.walk(directory).next()[1]
    except StopIteration:
        # no dir here, it seems
        print "Directory not found: {}".format(directory)
        return

    if len(dirs) > 0:  # rename subdirs first
        for d in dirs:
            rerename(os.path.join(directory, d))

    print "Renaming " + directory
    path, base = os.path.split(directory)
    try:
        os.rename(directory, os.path.join(path, base.lower()))
    except OSError:
        print "Error detected. This is usually caused by having directories " \
                "that differ only in case (a and A as subdirectories of the " \
                "same directory)."


if __name__ == '__main__':
    print "lower - recursively rename directories to be lowercase."
    if len(sys.argv) < 2:
        print "usage: lower <directory>"
    else:
        rerename(sys.argv[1])
