#!/usr/athena/bin/perl

umask(002);

$rootdir = "/rtfm/faq_server";

push(@INC, $rootdir);

require 'faqservvars.pl';
require 'syslog.pl';

$post = $post_faq;
$prog = "FAQ server poster";

&openlog($prog, 'pid', $log_facility);

if (! open(LOCKFILE, ">$lockfile.$$")) {
    &syslog('err', "opening %s for write: %m", $lockfile);
    $output .= "Opening $lockfile: $!.\n";
    &finished(1);
}

if (! print LOCKFILE "$$\n") {
    &syslog('err', "writing to %s: %m", $lockfile);
    $output .= "Writing to $lockfile: $!.\n";
    &finished(1);
}

close(LOCKFILE);

while (! link("$lockfile.$$", $lockfile)) {
    if (++$lock_count > 10) {
	&syslog('err', "couldn't establish lock; giving up");
	$output .= "Couldn't establish lock; gave up.\n";
	&finished(1);
    }
    sleep 10;
}

if (! open(POST, "$post -quiet 1 -config $configfile 2>&1|")) {
    &syslog('err', "running %s: %m", $post);
    $output .= "Running $post: $!.\n";
    &finished(1);
}

while (<POST>) {
    $postoutput .= $_;
    chop;
    &syslog('info', "post_faq output: %s", $_);
}

close(POST);

if ($?) {
    &syslog('err', "$post exited with non-zero status");
    $output .= "$post exited with non-zero status.\n";
    &finished(1);
}

&finished(0);

sub finished {
    unlink("$lockfile.$$", $lockfile);

    exit $_[0] if (! ($output || $postoutput));

    if (! open(MAIL, "|/usr/ucb/mail -s \'$prog output\' $administrator")) {
	&syslog('err', "executing /usr/ucb/mail: %m");
	die "Executing /usr/ucb/mail: $!.\n";
    }

    if (($output && (! print MAIL "$output\n")) ||
	($postoutput && (! print MAIL "Output of post_faq:\n\n$postoutput"))) {
	&syslog('err', "writing to /usr/ucb/mail: %m");
	die "Writing to /usr/ucb/mail: $!.\n";
    }

    close(MAIL);

    if ($?) {
	&syslog('err', "/usr/ucb/mail exited with non-zero status");
	die "/usr/ucb/mail exited with non-zero status.\n";
    }

    exit $_[0];
}
