#!/usr/local/bin/perl -w-- # -*- perl -*-
#
# $Id: fastcp,v 1.3 1994/09/10 18:11:57 qjb Exp $
# $Source: /home/qjb/scripts/RCS/fastcp,v $
# $Author: qjb $
#
# Given two files (or a source file and a destination directory),
# determine the host of the destination directory.  If local,
# cp src dest; otherwise, rcp src host:dest
#

# This code, from the perl manual page, forces this to be run by perl from 
# perl, sh, or csh.  It must be first.
eval '(exit $?0)' && eval 'exec /usr/local/bin/perl -S $0 ${1+"$@"}'
& eval 'exec /usr/local/bin/perl -S $0 $argv:q'
    if 0;

$whoami = ($0 =~ m,([^/]*)$,) ? $1 : $0;

&usage if (scalar(@ARGV) != 2);
($src, $dest) = @ARGV;
$src =~ s,/$,,;
$dest =~ s,/$,,;
$host = &hostof($dest);
$cmd = sprintf("%scp %s %s%s", ($host eq "") ? "" : "r",
	       $src, ($host eq "") ? "" : "$host:", $dest);
print $cmd, "\n";
exit system($cmd);

sub hostof {
    local($file) = @_;
    local($dirname, @fields, $mountpoint, $filesys, $host,
	  @stat, $dev, %hosttable);

    $dirname = (($file =~ m,^(.*)/([^/]+)$,) ? $1 : ".") . "/.";
    (stat $dirname) || die "$whoami: can't stat $dirname: $!\n";
    open(MOUNT, "mount|") || die "$whoami: can't run mount.\n";
    while(<MOUNT>)
    {
	chop;
	@fields = split;
	$filesys = $fields[0];
	$mountpoint = $fields[2];
	if (@stat = stat $mountpoint)
	{
	    $dev = $stat[0];
	    $host = (($filesys =~ m/(^[^:]*):/) ? $1 : "");
	    $hosttable{$dev} = $host;
	}
    }
    close(MOUNT);
    (@stat = stat $dirname) || die "$whoami: can't stat $dirname: $!\n";
    $dev = $stat[0];
    $hosttable{$dev};
}

sub usage {
    print STDERR "Usage: $whoami src dest\n";
    exit 1;
}
