#!/usr/bin/perl

# rename_for_windows
# This script renames all the files supplied as command-line args
# where necessary so that the filename is acceptable to MS Windows
# You could use the following command to run the script on all files
# and folders under the current folder:
#   find -d . -print0 | xargs -0 ~/rename_for_windows
#
# Cameron Hayne (macdev@hayne.net), June 2004

use strict;
use warnings;

chomp(@ARGV = <STDIN>) unless @ARGV;

# The Microsoft document at
# http://support.microsoft.com/default.aspx?scid=kb;EN-US;100108
# says that the following characters are not allowed in filenames
# in each of the specified filesystems:
# FAT:   .  "  /  \  [  ]  |  :  ;  ,  =
# NTFS:  ?  "  /  \  <  >  |  :  *

# We don't do anything with the dot (.) since it clearly is allowable
# in spite of what that document says.
# And we don't do anything with the slash (/) since that character
# will not occur in OS X filenames and modifying it would cause
# troubles when a file path (with directories) is specified.
# The changing of the filenames is done via the 'tr' statements below.
# Each occurrence of a character in the first curly brackets
# is replaced by the character in the second curly brackets.

foreach my $filename (@ARGV)
{
    my $orig_filename = $filename;

    $filename =~ tr{\\}{-};
    $filename =~ tr{*?}{X};
    $filename =~ tr{"><[]|:;,=}{_};

    unless ($filename eq $orig_filename)
    {
        print "About to rename $orig_filename to $filename\n";
        if (-e $filename)
        {
            print "Oops, there already exists a file named $filename\n";
            print "Skipping the rename - you will have to do it manually\n";
        }
        else
        {
            rename($orig_filename, $filename);
        }
    }
}
