#!/usr/local/bin/perl -w
# -*- perl -*-

# Cricket: a configuration, polling and data display wrapper for RRD files
#
#    Copyright (C) 1998 Jeff R. Allen and WebTV Networks, Inc.
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

#
# run a cricket subtree and send any output to the provided email addresses
#

use strict;
use Getopt::Long;
use Net::SMTP;
use Net::DNS;

my $result      = "";
my @output      = ();

my $doSubtree;

# Define your default email address here if you don't want to use -m
my $doMail = 'smrtg@corp.webtv.net';

# Define your SMTP host here
my $mx = 'smtplocal-2001-2.private.lawson.webtv.net';

$result = GetOptions(   "mail|m=s" => \$doMail,
                        "subtree|s=s" => \$doSubtree,
                    );

if (!$result) {
        die "Error handling options.\n";
}
if (!defined($doSubtree)) {
        die "Must provide a subtree to run.\n";
}

@output = `perl c:/crickethome/cricket/collect-subtrees $doSubtree 2>&1`;

if ($#output > 0) {
        my $res = Net::DNS::Resolver->new;
	# Define nameservers here if you don't have a libresolv (like on
	# Windows systems)
	#$res->nameservers('127.0.0.1');

        my ($eUser, $eDomain) = split(/\@/, $doMail);
        my @mx = mx($res, $eDomain);
        my $subject = "output from subtree " . $doSubtree;

	# Comment the $mx[0]->{'exchange'} line and uncomment the ($mx) line
	# if you don't want DNS to figure out the exchanger. It may not be
	# able to talk to the DNS-determined relay if you're behind a firewall.
	#my $smtp = Net::SMTP->new($mx[0]->{'exchange'});
	my $smtp = Net::SMTP->new($mx);

	$smtp->mail($doMail);
        $smtp->to($doMail);
        $smtp->data();
        $smtp->datasend("Subject: $subject");
        $smtp->datasend(@output);
        $smtp->dataend();
        $smtp->quit;
}

