#!/usr/bin/perl
# Prints an HTML document with links to the 
# web pages of all users who are currently 
# logged in.
# 
# Updates:
#  2003-08-13 msittig@freeshell.org
#  2004-04-25 msittig@freeshell.org

use CGI qw{ :standard };

my $debug = param('debug');
sub er { print "@_\n" if $debug == 1; }

&er( "Starting script." );
my $domain = "http://www.ugcs.caltech.edu/~USER/";
my $script_name = $0;
my $user = `whoami`; chomp $user;
my $host = `hostname`; chomp $host;
er( "Script run by $user.\n" );

my @user = `rwho -a | awk '{ print \$1 }' | sort -u`;
my $count = scalar @user;
er( "Users: $count.\n@user" );

my( @web_presence );
er( "Checking webpages... " );
foreach (@user) {
    my $url = $domain;
    chomp $_;
    $url =~ s/USER/$_/;
    unless( system( "wget -q --spider $url -O /dev/null 2>&1 > /dev/null" ) ) {
	er( "Success, found $url" );
	push( @web_presence, $url );
    } else {
	er( "$url 404" );
	open( ERR, "$HOME/bin/error.log" );
	print ERR "Couldn't access $url\n" ;
	close ERR;
    }
}
er( "done. \n@web_presence" );

my $plural = ( scalar @users == 1 ) ? "" : "s";
print header(-charset=>'utf-8'),
    start_html( { -title=>"$script_name script output" } ),
    h1( "Users with websites who are logged into UGCS servers now" ),
    strong( "Out of ".scalar @user." user$plural logged in, ".scalar @web_presence." have sites like $domain:" );

foreach( @web_presence ) {
    print p( a( { -href=>"$_" }, $_ ) );
}

print p( "$user thanks you for playing!" );
exit 0;

