#!/usr/bin/perl
# 
# $Id: apple_mv.in,v 1.1 2002/01/17 05:59:25 srittau Exp $

$USAGE = <<USAGE;
Usage: $0 filename1 filename2
       $0 filename ...  directory
Do an apple move, moving the resource fork as well
USAGE

@from = @ARGV; pop(@from);
$to = $ARGV[-1];

if (-f $to && @from > 1) { die $USAGE; }

foreach $from (@from) {
    if (!-f $from) {	
	print STDERR "file $from does not exist\n";
	die $USAGE;
    }

    if (!-d $to && @from >1) {
	print STDERR "directory $to does not exist\nCan't move multiple files into one file.\n";
	die $USAGE;
    }
    
    $from = escape_bad_chars($from);
    $to = escape_bad_chars($to);
    $cmd = "mv $from $to";
    system $cmd || die "error executing $cmd";
    
    ($from_dir, $from_file) = split_dir_file($from);

    if (-d $to) {
	if (!-d "$to/.AppleDouble") {
	    mkdir("$to/.AppleDouble", 0777);
	}
	$cmd = "mv $from_dir/.AppleDouble/$from_file $to/.AppleDouble/$from_file";
    } else {
	($to_dir, $to_file) = split_dir_file($to);

	if (!-d $to_dir) {
	    print STDERR "directory $to does not exist\n";
	    die $USAGE;
	}
    
	if (!-d "$to_dir/.AppleDouble") {
	    mkdir("$to_dir/.AppleDouble", 0777);
	}
	$cmd = "mv $from_dir/.AppleDouble/$from_file $to_dir/.AppleDouble/$to_file";
    }

    system $cmd || die "error executing $cmd";
}

sub escape_bad_chars {
    my($file) = @_;
    $file=~s/([^a-zA-Z0-9.-_])/\\$1/;
    return $file;
}

# split a file path into a directory and file name.
sub split_dir_file {
    my $path = shift;

    @path_elems = split(/\//, $path);

    my $file = pop(@path_elems);
    my $dir;
    if (!@path_elems) {
	$dir = '.';
    } else {
	$dir = join('/', @path_elems);
    }

    $dir, $file;
}


