#!/mit/watchmaker/vaxbin/perl
        eval "exec /mit/watchmaker/vaxbin/perl -S $0 $*"
                if $running_under_some_shell;

# $Header: patftp.SH,v 2.0.1.1 88/08/05 00:29:52 lwall Exp $
#
# $Log:	patftp.SH,v $
# Revision 2.0.1.1  88/08/05  00:29:52  lwall
# patch1: now depends on perlpath
# 
# Revision 2.0  88/06/28  23:19:57  lwall
# Baseline.
# 

$orgname='MIT Project Athena';

chop($orgname = `cat $orgname`) if $orgname =~ m|^/|;

chdir '..' if -f '../.package';

do readpackage();

if ($#ARGV < 0) {
    open(PL,"patchlevel.h") || die "Can't open patchlevel.h\n";
    while (<PL>) {
        $argv = $1 if /^#define\s+PATCHLEVEL\s+(\d+)/;
    }
    close PL;
    die "Malformed patchlevel.h file.\n" if $argv eq '';
    @ARGV = $argv;
}
else {
    for (@ARGV) {
	s/^patch//;
    }
    $argv = do rangeargs(@ARGV);
    @ARGV = split(' ',$argv);
}

if ($#ARGV < 0) {
    die "No patches specified.\n";
}
elsif ($#ARGV) {
    print "Copying $package $baserev patches $argv to $ftpdir...\n";
}
else {
    print "Copying $package $baserev patch $argv to $ftpdir...\n";
}

chdir 'bugs' || die "Can't cd to bugs\n";

until ($#ARGV < 0) {
    $patnum = shift;
    `cp patch$patnum $ftpdir`;
}

sub readpackage {
    if (! -f '.package') {
        if (-f '../.package' || -f '../../.package') {
            die "Run in top level directory only.\n";
        }
        else {
            die "No .package file!  Run packinit.\n";
        }
    }
    open(package,'.package');
    while (<package>) {
        next if /^:/;
        next if /^#/;
        if (($var,$val) = /^\s*(\w+)=(.*)/) {
            $val = "\"$val\"" unless $val =~ /^['"]/;
            eval "\$$var = $val;";
        }
    }
    close package;
}

sub rangeargs {
    local($result) = '';
    local($min,$max,$_);
    open(PL,"patchlevel.h") || die "Can't open patchlevel.h\n";
    while (<PL>) {
        $maxspec = $1 if /^#define\s+PATCHLEVEL\s+(\d+)/;
    }
    close PL;
    die "Malformed patchlevel.h file.\n" if $maxspec eq '';
    while ($#_ >= 0) {
	$_ = shift(@_);
	while (/^\s*\d/) {
	    s/^\s*(\d+)//;
	    $min = $1;
	    if (s/^,//) {
		$max = $min;
	    }
	    elsif (s/^-(\d*)//) {
		$max = $1;
		if ($max == 0 && $maxspec) {
		    $max = $maxspec;
		}
		s/^[^,],?//;
	    }
	    else {
		$max = $min;
	    }
	    for ($i = $min; $i <= $max; ++$i) {
		$result .= $i . ' ';
	    }
	}
    }
    $result;
}
