#!/usr/local/bin/perl -I/usr/local/lib/perl
$rcsid = "$Id: drbert,v 1.1 1994/12/14 20:55:18 edburns Exp edburns $";
require "getopts.pl";

die "This program requires that DISPLAY is set to a vaild X server.\n" unless ($DISPLAY=$ENV{'DISPLAY'});
$maxtries = 3;
$opt_i = "128.123.122.20";	# default ip
$opt_p = 6182;
$opt_f = 1;			# get Dr. Fun by default
$opt_v = " -root -quit ";

&Getopts('i:p:v:bfdh');

if ($opt_h) {
    die "usage: drbert [-i ip number] [-i p port] [-f get dr.fun] [-d get dilbert]\n [-b get wtbr] [-v \"xvoptions\"] ";}

$retval = &MCCIInitialize;
$callBack = "perlCB";
@cbd = "perlCBD";
$CCIPort = &MCCIConnect($opt_i, $opt_p, $callBack, @cbd);

if (&MCCIIsConnected($CCIPort)) {
    if ($opt_b) {
	$webfile = &webGrab("http://xor.com/wtbr/Todays.GIF", "image/gif");
    } elsif ($opt_d) {
	$webfile = &webGrab("http://www.cen.uiuc.edu/cgi-bin/read-comics?today", "image/gif");
    } else {
	$webfile = &webGrab("http://sunsite.unc.edu/Dave/Dr-Fun/latest.jpg", "image/jpeg");
    }
    $disconnect = &MCCIDisconnect($CCIPort);
} else {
    die "not connected to $opt_i:$opt_p, maybe try again later.\n";
}

exec "xv $opt_v $webfile" if -e $webfile;

exit;

sub webGrab {
    local($url, $mt) = @_;
    local($file,$i);
    $webCB = "webCB";	

    ($junk,$ext) = split(/\//, $mt);
    $file = "/tmp/aa$$.$ext";
    @webcbd = ($file);
    for ($i = 0; $i < $maxtries; $i++) {
	if (!&MCCISendOutput($CCIPort, $mt, $webCB, @webcbd) ) {
	    if ($MCCI_OK != &MCCIGet($CCIPort,$url,$MCCI_DEFAULT,$MCCI_DEFAULT,$head)) {
		print "unable to get $url\n";
	    }
	    &MCCISendOutputStop($CCIPort, $mt);
	    last;
	}
    }
    return $file;
}

sub perlCB {
  return 0;
}

sub webCB {
    local($mt, $data, $len, @file) = @_; 
    open(IMG, ">$file[0]");
    print IMG $data;
    close(IMG);
}

    
