#!/store/bin/perl

##
# Fetches all crontabs on the hosts specified on the command line
# and presents them sorted on user, machine and time.
# 
# @author Petter Reinholdtsen <pere@td.org.uit.no>
# @params host1 [host2 ...]
# @made 1996-07-27
# @version $Id: cron-summary,v 1.1 2003/06/02 13:01:37 pere Exp $
sub about {}

$crondir = "/var/spool/cron/crontabs";
$rsh = $ENV{RSH} || 'rsh';

@hosts = @ARGV;

foreach $host (@hosts) {
    @users = &get_cronusers($host);
    print "Users at $host: ".join(",", @users)."\n";
    foreach $user (@users) {
	&parse_crontab($host, $user);
    }
}

&show_cronsummary();

##
# Fetches the contents of $crondir from $host and returns all users as
# an array
#
# @params $host
# @return @users
sub get_cronusers {
    local($host) = @_;
    local($res) = `$rsh $host echo $crondir/\\*`;
    $res =~ s%$crondir/%%g;
    local(@users) = split(/\s+/, $res);
    return @users;
}

##
# Fetches the crontab-file for $user from $host and stores the info in
# @cron.
# @params $host, $user
# @return "" on failures and "1" on success.
sub parse_crontab {
    local($host, $user) = @_;
    open(CRONTAB, "rsh $host cat $crondir/$user|") || 
	die "Unable to open crontab on $host for $user";
    while (<CRONTAB>) {
	next if (/^\#/);
	($min, $hour, $dom, $moy, $daw, $command) = 
	    m/^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+)$/;
	push(@cron,join(":", $user, $host, $hour, $min, $dom, $moy, $daw, $command));
    }
    close(CRONTAB);
    return "1";
}

##
# Prints the crontab summary based on the info in @cron
sub show_cronsummary {
    local($lastuser, $lasthost);
    foreach $line (sort @cron) {

	($user) = m/^(.+):/;
	($user, $host, $hour, $min, $dom, $moy, $daw, @command) =
	    split(/:/, $line);
	if ($user ne $lastuser) {
	    print "\nUser: $user\n";
	    $lasthost = "";
	}
	print " Host: $host\n" if ($host ne $lasthost);
	$lastuser = $user;
	$lasthost = $host;
	
	print "  $line\n";
    }
}
