#! @PERL@ -w
# $Id: zmailnotify.in,v 1.6 2001/04/17 11:15:20 mattiasa Exp $

use strict;

my $pushpath = '@KRB_PUSH_PATH@';

my @mails;
my $mailhashref;

$ENV{PATH} = $ENV{PATH} . ":" . $pushpath;

open (PUSH, 'push --headers="from:,to:,subject:,message-id:"|') or die "Can't find push";

while(<PUSH>) {
    my $line = $_;
    if(!($line =~ /^$/)) {
	$line =~ /^(\S+):\s*(.*)$/;
	$mailhashref->{lc($1)} = $2;
    } else {
	push (@mails, $mailhashref);
	$mailhashref = {};
    }

}

close PUSH;

@mails = reverse @mails;

my $lockfrom = "";
my $lockto = "";
my $locksubject = "";
my $lockmessageid = "";

if (open(LOCK, $ENV{'HOME'} . "/.maillock")) {
    $lockfrom = <LOCK>;
    chomp $lockfrom if defined $lockfrom;
    $lockto = <LOCK>;
    chomp $lockto if defined $lockfrom;
    $locksubject = <LOCK>;
    chomp $locksubject if defined $lockfrom;
    $lockmessageid = <LOCK>;
    chomp $lockmessageid if defined $lockfrom;
}

close LOCK;

my $i= ($#mails < 4) ? $#mails +1 : 4 ;

my $from;
my $to;
my $subject;
my $messageid;

my $first = 0;

foreach my $mail (@mails) {

    $from = defined $$mail{'from'} ? $$mail{'from'} : "" ;
    $to = defined $$mail{'to'} ? $$mail{'to'} : "";
    $subject = defined $$mail{'subject'} ? $$mail{'subject'} : "";
    $messageid = defined $$mail{'message-id'} ? $$mail{'message-id'} : "";

    if (($from eq $lockfrom and $to eq $lockto and $subject eq $locksubject and $messageid eq $lockmessageid) or $i == 0) {
	last;
    }

    if($first == 0) {

	if(open(WRITELOCK, ">" . $ENV{'HOME'} . "/.maillock")) {
	    print WRITELOCK $from . "\n";
	    print WRITELOCK $to . "\n";
	    print WRITELOCK $subject . "\n";
	    print WRITELOCK $messageid . "\n";
	}
	close WRITELOCK;
	$first=1;
    }

    open(ZWRITE, "|zwrite -d -q -s '' -c mail -i popret " . $ENV{'USER'}) or die;

    print ZWRITE "From: $from\n";
    print ZWRITE "To: $to\n";
    print ZWRITE "Subject: $subject\n";

    close(ZWRITE);

    $i--;
}

exit 1;
