#!/usr/bin/perl -w

use strict;
use vars qw(@quotes $load_quotes $load_sighead $home $sighead @signature %opt);
use POSIX;
use Sys::Syslog;
use Getopt::Std;
use FileHandle;

$0 = "signature.pl";

sub perish ($) {
    my ($reason) = @_;
    if ($opt{d}) {
	syslog 'warning', $reason;
	warn $0 . ': ' . $reason . "\n" if $opt{n};
	exit 1;
    } else {
	die $0 . ': ' . $reason . "\n";
    }
}

sub notify ($) {
    my ($matter) = @_;
    if ($opt{d}) {
	syslog 'notice', $matter;
	warn $0 . ': ' . $matter . "\n" if $opt{n}
    } else {
	warn $0 . ': ' . $matter . "\n";
    }
}

sub inform ($) {
    &notify(@_) if $opt{v};
}

sub version () {
    print <<'EOM';
signature, v0.0, Copyright (C) 2001 Sebastian Marius Kirsch
<skirsch@moebius.inka.de>, all rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
EOM

    exit;
}

sub start_daemon () {
    my $signature = $home . '/.signature';
    chomp(my $hostname = `hostname`);
    my $pidfile = $home . '/.signature-' . $hostname;

    my $cleanup = sub {
        close PIDFILE;
	unlink $pidfile or &notify("problems removing $pidfile: $!");
	unlink $signature or &notify("problems removing signature: $!");
	my $SIGNATURE = new FileHandle($signature, 'w') or &perish("could not write signature: $!");
	print $SIGNATURE @signature;
	undef $SIGNATURE;
	closelog;
	exit 0;
    };

    openlog 'signature', 'pid', 'user';

    
    fork() && exit unless $opt{n};
    
    while (!sysopen(PIDFILE, $pidfile, O_CREAT|O_WRONLY|O_EXCL)) {
	my $PIDFILE = new FileHandle($pidfile, 'r') or &perish("could not open $pidfile for reading"); 
	chomp(my $pid = <$PIDFILE>);
	if ($pid > 0) {
	    if (kill 0, $pid) {
		exit;
	    } else {
		&notify("stale lock file from process $pid");
		undef $PIDFILE;
		unlink $pidfile;
	    }
	}
    }
    autoflush PIDFILE;
    print PIDFILE "$$\n";
    
    unless (-p $signature) {
	unlink $signature or &notify("cannot remove $signature: $!") if (-f $signature);
	mkfifo $signature, oct 666 or &perish("cannot make FIFO $signature: $!");
    }
	
    $SIG{HUP} = \&load_quotes;
    $SIG{TERM} = $cleanup;
    $SIG{INT} = $cleanup;
    
    while (1) {
	open SIGNATURE, '> ' . $signature or &perish("cannot open FIFO $signature: $!");
	print SIGNATURE @signature;
	print SIGNATURE &get_cookie();
	close SIGNATURE;
	select(undef, undef, undef, 0.1);
    }
}


sub load_quotes () {
    &inform("reloading cookies");
    if (defined @quotes) { seek DATA, $quotes[0], 0; }
    @quotes = (tell DATA);
    
    while (<DATA>) {
	if (/^%$/) { push @quotes, tell DATA; }
    }
    
    push @quotes, tell DATA; 
    return $load_quotes = (stat DATA)[9];
}

sub load_sighead () {
    &inform("reloading signature head");
    if (my $SIGHEAD = new FileHandle($sighead, 'r')) {
	@signature = <$SIGHEAD>;
	undef $SIGHEAD;
    } else {
	notify "could not open $sighead: $!";
    }
    return $load_sighead = (stat $sighead)[9];
}
	
sub get_cookie () {
    if (-f $sighead) { ($load_sighead < (stat $sighead)[9]) && &load_sighead; }
    ($load_quotes < (stat DATA)[9]) && &load_quotes;
    my $quote;
    my $pos = rand $#quotes;
    seek DATA, $quotes[$pos], 0;
    read DATA, $quote, $quotes[$pos + 1] - $quotes[$pos] - 2;
    return $quote
}

$home = (getpwuid($<))[7]; 
$sighead = $home . '/.sighead';

&load_quotes; &load_sighead;

srand(time() ^ ($$ + ($$ << 15)));

getopts('dvVn', \%opt);

$opt{V} && &version;

if ($opt{d}) { start_daemon(); } else {
    if (exists $ENV{GATEWAY_INTERFACE}) {
	print STDOUT "Content-type: text/plain\n\n";
    } else {
	print STDOUT @signature;
    }

    print STDOUT get_cookie();
    close STDOUT;
    exit;
}    

__DATA__
fortune cookie
%
another fortune cookie
%
a third fortune cookie
%

