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

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

die $USAGE if @ARGV < 2;

@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 copy multiple files into one file.\n";
	die $USAGE;
    }
    
    $cmd = "cp '$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 = "cp '$from_dir/.AppleDouble/$from_file' '$to/.AppleDouble/$from_file'";
    } else {
	($to_dir, $to_file) = split_dir_file($to);
	if (!-d "$to_dir/.AppleDouble") {
	    mkdir("$to_dir/.AppleDouble", 0777);
	}	
	$cmd = "cp '$from_dir/.AppleDouble/$from_file' '$to_dir/.AppleDouble/$to_file'";
    }

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

# 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;
}


