use Win32::ChangeNotify;
use Mail::Sendmail;
# use Net::SNPP;
use strict;
my (@stat, $beginsize, $notify, $endsize, %mail,
	$to, $from, $directory, $file, $machine,
	$snpp, $pagerhost, $pager,
	@drwatson, $drw, $pid, $app,
	);
my $VERSION = 0.42;

$machine = 'machinename';
$to = 'notify@address.com';
$from = "$machine\@address.com";
$directory = 'c:/winnt';
$file = 'c:/winnt/drwtsn32.log';

# $pagerhost = 'pager.service.com';
# $pager = 'pagerID';

print "Monitoring Dr Watson on $machine ...\n";

while (1)	{
	@stat = stat("$file");
	$beginsize=$stat[7];
	$notify = Win32::ChangeNotify->new($directory,0,'SIZE')
			or die "$^E";
	$notify->wait or warn "Something failed: $!\n";

	# There has been a change.
	@stat = stat($file);
	$endsize=$stat[7];

	# Did the Dr Watson log change?
	if ($beginsize != $endsize)	{
		print "Crash ...\n";

 		open (DRW, $file);
 		@drwatson=<DRW>;
 		close DRW;
 
 		$drw = join '',@drwatson;
 		$drw =~ m/.*Application exception occurred:.*?pid=(\d+)/s;
 		$pid = $1;
 
 		$drw =~ m/.*$pid\s(.*?)\n/s;
 		$app = $1;
 
 		print "The crash was in $app (PID $pid)\n";
 
 		# Send notification
 		%mail = (To => $to,
 			From => $from,
 			Subject => "Crash on $machine",
 			Message => "$machine crashed in $app."
 			);
 		sendmail(%mail) or die $Mail::Sendmail::error;
 		print "Notification sent\n", $Mail::Sendmail::log;
 
 		#  Or, send a page
 		# $snpp = Net::SNPP->new($pagerhost);
 		# $snpp->send (Pager => $pager,
 		# 			Message => "$machine crashed in $app."
 		# 			);
 		# 
 		# print "Page sent to $pager.\n";
 	} #  End if
 
} #  Wend
 
=head1 NAME

monitor_drw - Report when an NT box crashes by watching the size
of the Dr Watson log.

=head1 DESCRIPTION

It is rather difficult to tell, sometimes, when an application has crashed
on an NT machine without actually looking at the screen. You can try to
ping, or even establish socket connections, but these can produce 
misleading results. If you have Dr Watson installed, you can use this 
script to monitor the size of the Dr Watson log, and send you email when
there is a crash, or send an alpha page.

=head1 PREREQUISITES

This script requires the C<strict>, C<Win32::ChangeNotify> and
C<Mail::Sendmail> modules. And, obviously, since it monitors
the Dr Watson log, it would help to have Dr Watson (or similar) installed.

=head1 COREQUISITES

If you have a pager server, you might want to use C<Net::SNPP> to send alpha
pages to your pager. Just uncomment the relevant lines, and maybe comment
out the lines that send email. That's how I have it running.

=head1 README

Monitors the Dr Watson log file on your NT machine, and sends you email,
or, optionally, an alpha page, when Dr Watson detects a crash on your 
machine.

=pod OSNAMES

MSWin32

=pod SCRIPT CATEGORIES

Win32

=cut
