#!/usr/local/bin/perl -w-- # -*- perl -*-
#
# $Id: rtapecopy,v 1.4 1995/11/01 19:00:30 ejb Exp $
# $Source: /home/ejb/scripts/RCS/rtapecopy,v $
# $Author: ejb $
#

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

require 5.000;
use strict;

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

my $def_blocksize = 20;

&usage() if (@ARGV != 2);
my ($src, $dest) = @ARGV;

my ($suser, $shost, $sdev) = &check_dev($src);
my ($duser, $dhost, $ddev) = &check_dev($dest);

my $scommand = "dd if=$sdev ibs=${def_blocksize}b obs=${def_blocksize}b";
my $dcommand = "dd of=$ddev ibs=${def_blocksize}b obs=${def_blocksize}b";

if ($shost ne "")
{
    my $user = "";
    if ($suser ne "")
    {
	$user = "-l $suser";
    }
    $scommand = "rsh $shost $user -n \"" . $scommand . "\"";
}

if ($dhost ne "")
{
    my $user = "";
    if ($duser ne "")
    {
	$user = "-l $duser";
    }
    $dcommand = "rsh $dhost $user \"" . $dcommand . "\"";
}
print "Source command: $scommand\n";
print "Dest command: $dcommand\n";

$| = 1;
my $i = 0;
while (1)
{
    print "Copying file $i\n";

    #
    # Create pipes for running rsh/dd commands through
    # so that we can look at the output.
    #
    pipe(*SFR, *SFW) || die "$whoami: pipe: $!";
    pipe(*DFR, *DFW) || die "$whoami: pipe: $!";
    my $sf = fileno(SFW);
    my $df = fileno(DFW);
    select(*SFR); $| = 1;
    select(*DFR); $| = 1;
    select(STDOUT);

    #
    # Run the commands redirecting the source command through one
    # pipe and the dest through another.
    #
    defined(my $pid = fork) || die "fork: $!";
    if ($pid)
    {
	close(SFW);
	close(DFW);
    }
    else
    {
	close(DFR);
	close(SFR);
	exit exec("$scommand 2>&$sf | $dcommand 2>&$df");
    }

    #
    # Print and save the output.
    #
    my $sr = '';
    my $dr = '';
    while (<SFR>)
    {
	$sr .= $_;
	print "src: $_";
    }
    while (<DFR>)
    {
	$dr .= $_;
	print "dest: $_";
    }
    $i++;
    close(SFR);
    close(DFR);

    #
    # If the source command copied no data, quit.
    #
    last if ($sr eq "0+0 records in\n0+0 records out\n");
}
printf("Copied $i file%s\n", ($i == 1) ? "" : "s");

sub usage
{
    print STDERR "Usage: $whoami src_tape dest_tape\n";
    print STDERR "  tapes may be user\@host:/dev/whatever\n";
    print STDERR "  XXX: NOTE: This command depends upon the format of " .
	"the output of dd and\n";
    print STDERR "     on the name of rsh.\n";
    exit 2;
}

sub check_dev
{
    my ($user, $host, $device) = ("", "", "");
    my $dev = shift;
    if ($dev =~ m,:,)
    {
	if ($dev =~ m,^(.*)\@(.*):(.*)$,)
	{
	    ($user, $host, $device) = ($1, $2, $3);
	}
	else
	{
	    $dev =~ m/^(.*):(.*)$/;
	    ($host, $device) = ($1, $2);
	}
    }
    else
    {
	$device = $dev;
    }

    ($user, $host, $device);
}
