#!/usr/bin/perl -w
#----------------------------------------------------------------------
# mdevent: Handle events from mdadm --monitor
#----------------------------------------------------------------------
# Copyright (C) 2006 Shad L. Lords <slords@mail.com>
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
#----------------------------------------------------------------------

package esmith;

use strict;

use esmith::ConfigDB;
use esmith::util;
use esmith::db;

use Text::Template;

my $conf = esmith::ConfigDB->open_ro;

my $event = $ARGV [0];
my $device = $ARGV [1];
my $member = $ARGV [2] || '';

print "Event: $event, Device: $device, Member: $member\n";

if ($event =~ m#^Rebuild# && system( "ps -C raid-check" ) == 0 ) {
    exit 0;
}

if ($event =~ m#^Rebuild|^Fail|^Degraded|^SpareActive#) {
    my $domain = $conf->get_value("DomainName") || 'localhost';
    my $user = "admin_raidreport\@$domain";

    my $templates = '/etc/e-smith/templates';
    my $source = '/usr/lib/e-smith-mdevent/mdEvent.tmpl';

    -f "${templates}-custom${source}" and $templates .= "-custom";

    my $t = new Text::Template(TYPE => 'FILE',
    SOURCE => "${templates}${source}");

    open(QMAIL, "|/var/qmail/bin/qmail-inject -froot\@$domain $user")
    || die "Could not send mail via qmail-inject!\n";

    print QMAIL $t->fill_in( HASH => {
        conf    => \$conf,
        user    => $user,
        event   => $event,
        device  => $device,
        member  => $member,
    });

    close QMAIL;
}
