#! /usr/bin/env python

# change-filename-encoding --- Change a file name encoding
# Copyright (c) 2006 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, getopt

progname = os.path.basename(sys.argv[0])
usage = """Usage: %s [OPTION...] FILE...
Change the encoding of a file name in the filesystem.

The encoding of every given FILE name is changed from ORIG-ENCODING
(argument of --from) to TARGET-ENCODING (argument of --to).
Both --from and --to must be provided.

The valid encodings are listed in the documentation for the Python
'codecs' module in
<python documentation root>/html/lib/standard-encodings.html.
They include 'iso-8859-1', 'iso-8859-15' and 'utf-8'.

Options:

  -f, --from=ORIG-ENCODING    original encoding of the file name
  -t, --to=TARGET-ENCODING    target encoding for the file name
      --help                  display usage information and exit""" % progname


def main():
    try:
        # Options processing
        opts, args = getopt.getopt(sys.argv[1:], "f:t:",
                                   ["from=",
                                    "to=",
                                    "help"])
    except getopt.GetoptError, message:
        sys.exit(usage)

    if len(args) == 0:
        sys.exit(usage)

    # Default values for options
    orig_encoding = None
    target_encoding = None

    # Read command-line options
    for option, value in opts:
        if option == "--help":
            print usage
            sys.exit(0)
        elif option in ("-f", "--from"):
            orig_encoding = value
        elif option in ("-t", "--to"):
            target_encoding = value
        else:
            sys.exit(usage)

    if (orig_encoding is None) or (target_encoding is None):
        sys.exit("%s: both --from and --to must be provided" % progname)

    for file_path in args:
        file_dir = os.path.dirname(file_path)
        orig_file_name = os.path.basename(file_path)
        new_file_name = \
                      orig_file_name.decode(orig_encoding).encode(target_encoding)

        os.rename(file_path, os.path.join(file_dir, new_file_name))

    sys.exit(0)

if __name__ == "__main__": main()
