#	$RCSfile: notify.pl,v $
#	$Revision: 1.8 $
#	$Author: marten $
#	$Date: 1994/10/05 12:44:42 $

# notify.pl - implements the notify function.

require "encmp.pl";
require "enwrite.pl";
require "entype.pl";

# It consists of two parts. One is the part that writes out the objects
# to temp files, one temp file per notifier, and this is called from
# updatecheck, the second part should be called at the end of an update
# from dbupdate, and will actually mail out the notify messages.

sub AddNotify {

    local(*old, *new) = @_;
    local($j);

    local($delete) = 1 if (!&entype(*new));
    local($type) = &entype(*old);

    if ($old{"ny"} && !&encmp(*new, *old)) {
	local(@notifiers) = split(/\n/, $old{"ny"});

	# If there is a delete, add all guardians as notifiers.
	# This will go away I hope. Cannot assume all guardians
	# have a local account any more with new scheme.

	if ($delete) {
	    foreach (split(/\s+/, $GRD{$type})) {
		foreach $j (split(/\s+/, $old{$_})) {
		    @notifiers = (@notifiers, $j);
		}
	    }
	}
	&DoAddNotify(*notifiers, *old, *new, $delete);
    }
}

sub DoAddNotify {
    local(*notifiers, *old, *new, $delete) = @_;

    return if &encmp(*old, *new);

    foreach (@notifiers) {
	if (!$notify{$_}) {
	    $notify{$_} = &NotifyTmpFile($_);
	    open(NOTIFY, ">$notify{$_}") ||
		&syslog("ERRLOG", "Cannot create notify file $notify{$_}");
	    &WriteNotifyHeader(NOTIFY, $_);
	} else {
	    open(NOTIFY, ">>$notify{$_}") ||
		&syslog("ERRLOG", "Cannot open notify file $notify{$_}");
	}
	select(NOTIFY);
	if ($delete) { # Deletion
	    print "---\n";
	    print "OBJECT BELOW DELETED:\n\n";
	    print "\n" if &enwrite(*old,1,0,1);
	} elsif (!&entype(*old)) {
	    print "---\n";
	    print "OBJECT BELOW CREATED:\n\n";
	    print "\n" if &enwrite(*new,1,0,1);
	} else {
	    print "---\n";
	    print "PREVIOUS OBJECT:\n\n";
	    print "\n" if &enwrite(*old,1,0,1);
	    print "REPLACED BY:\n\n";
	    print "\n" if &enwrite(*new,1,0,1);
	}
	close(NOTIFY);
    }
    select(STDOUT);
}


sub NotifyTmpFile {

    local($notifier) = @_;

    return "$TMPDIR/$notifier.$$";
}

sub WriteNotifyHeader {

    local($filehandle, $notifier) = @_;

    select($filehandle);

    print $NHEADER;
    $notifier = $DEFMAIL if $TESTMODE;
    print "To: $notifier\n";
    print "\n";

    eval "print \"$NOTITXT\n\";";

    select(STDOUT);
}    


sub SendNotifications {

    local($a);

    foreach $a (keys %notify) {
	system("$MAILCMD < $notify{$a}");
	unlink($notify{$a});
    }
}
