#! /usr/bin/env python

# flo-chcase --- Change the case in file names
# Copyright (c) 2004 Florent Rougon
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 dated June, 1991.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING. If not, write to the
# Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA  02110-1301 USA.

import sys, os, os.path, getopt, locale


# Python < 2.3 compatibility
if sys.hexversion < 0x02030000:
    # The assignments would work with Python >= 2.3 but then, pydoc
    # shows them in the DATA section of the module...
    True = 0 == 0
    False = 0 == 1


usage = """Usage: %s [OPTION]... FILENAME...
Convert a set of file names to uppercase or lowercase.

Return:
   - 0 if no error occurred;
   - 1 otherwise.

Options:
  -l, --lowcase             convert to lowercase
  -u, --upcase              convert to uppercase
      --help                display this message and exit""" \
  % os.path.basename(sys.argv[0])


def rename_files(lowcase, paths):
    for path in paths:
        fname = os.path.basename(path)
        if lowcase:
            new_fname = fname.lower()
        else:
            new_fname = fname.upper()

        os.rename(path, os.path.join(os.path.dirname(path), new_fname))


def main():
    map(lambda x: locale.setlocale(x, ''),
        (locale.LC_CTYPE,))

    try:
        opts, args = getopt.getopt(sys.argv[1:], "lu",
                                   ["help",
                                    "lowcase",
                                    "upcase"])
    except getopt.GetoptError, message:
        sys.stderr.write(usage + "\n")
        sys.exit(1)

    # Default values for options
    lowcase = False
    upcase = False
    
    for option, value in opts:
        if option in ("-l", "--lowcase"):
            lowcase = True
        elif option in ("-u", "--upcase"):
            upcase = True
        elif option == "--help":
            print usage
            sys.exit(0)
        else:
            sys.exit(
                "Unexpected option received from the getopt module; "
                "probably\na bug in %s" % os.path.basename(sys.argv[0]))

    if (lowcase and upcase):
        sys.exit("Unable to convert to both uppercase and lowercase at the "
                 "same time!")

    if (not lowcase) and (not upcase):
        sys.exit("No option specifying the type of renaming to perform.\n"
                 "Either -l (--lowcase) or -u (--upcase) must be given.")

    if len(args) < 1:
        sys.stderr.write(usage + "\n")
        sys.exit(1)

    try:
        rename_files(lowcase, args)
    except os.error, v:
        if v.filename is not None:
            err_msg = "%s: %s" % (v.filename, v.strerror)
        else:
            err_msg = v.strerror
        sys.exit(err_msg)

    sys.exit(0)


if __name__ == "__main__": main()
