#!/usr/local/bin/perl
# Copyright (c) May 1997 Wolfram Schneider <wosch@FreeBSD.org>, Berlin.
#
# rshell - a front end for rsh(1) and rcp(1)
#
# usage: rshell [rsh options] hostalias [rsh args]
#	 rcopy	[rcp options] hostalias:file ...
#
#
# $Id: rshell.pl,v 1.3 1997/06/09 21:10:19 wosch Exp wosch $

require 'getopts.pl';

# default configuration file for rshell
$rshrc = "$ENV{'HOME'}/.rshellrc";

$rsh = 'rsh'; $rcp = 'rcp';
%opt = ('rsh', 'Kdnxt:k:l:', 'rcp', 'Kprx:k');
@argv = @ARGV;

$debug = 1; # 0: no messages, 1: messages, 2:show only, no execute

sub usage {
    print "usage: rshell [rsh options] hostalias [rsh args]\n";
    print "usage: rcopy [rcp options] hostalias:file ...\n";
    print "\nhostaliases:\n";

    foreach (sort keys %aliases) {
	print "$_ -> $aliases{$_}\n";
    }
    print "\n";
    exit(1);
}

sub options {
    local($args) = @_;
    local(@argslist, @a);

    @a = split(/ */, $args);
    for($i = 0; $i <= $#a; $i++) {
	$_ = $a[$i];
	next if $_ eq ':';
	
	if ($a[$i + 1] eq ':') {
	    push(@arglist, ('-' . $_, eval "\$opt_$_")) if eval "\$opt_$_";
	} else {
	    push(@arglist, '-' . $_) if eval "\$opt_$_";
	}
    }
    @arglist;
}

# execute basic command (rsh/rcp)
sub Exec {
    local($command, @args) = @_;
    
    unshift(@args, &options($opt{$command}));
    if ($debug > 0 ) {
	print "$command @args\n";
	exit 0 if $debug > 1;
    }
    exec $command, @args;
}

# read rshell database ~/.rshellrc
open(RC, $rshrc) || do {
    warn "$rshrc: $!\n";
};

undef %aliases;
while(<RC>) {
    next if /^\s*$/ || /^\s*#/;	 # ignore comments

    #	# Program name for the remote shell command
    #	program </usr/bin/rsh>
    if (/^\s*program\s+(\S+)/) {
	$rsh = $1;
    }

    #	# Aliases for host names and E-Mail addresses
    #	alias	<hostname alias> <full hostname>
    #	alias	<host,host2,...> <email@hostname>
    elsif (/^\s*alias\s+(\S+)\s+(\S+)/) {
	for (split(/,/, $1)) {
	    $aliases{$_} = $2;
	}
    }
}

# check and call rsh(1)
if ($0 =~ m%(/|^)rshell%) {
    &Getopts($opt{'rsh'});
    &usage if $#ARGV < 0;
    $host = $ARGV[0]; shift @ARGV;
    if (defined($aliases{$host})) {
	if ($aliases{$host} =~ /^([^\@\s]+)\@([^\@\s]+)/) {
	    $opt_l = $1 if !$opt_l;
	    &Exec('rsh', $2, @ARGV);
	} else {
	    &Exec('rsh', $aliases{$host}, (&options, @ARGV));
	}
    } else {
	&Exec('rsh', $host, @ARGV);
    }
}

# check and call rcp(1)
else {
    &Getopts($opt{'rcp'});
    &usage if $#ARGV < 1;
    local(@a);
    foreach (@ARGV) {
	if (m%^([^/:]+):(.+)%) {
	    if (defined($aliases{$1})) {
		push(@a, "$aliases{$1}:$2");
	    } else { push(@a, $_); }
	} else {
	    push(@a, $_);
	}
    }
    &Exec('rcp', @a);
}
