#!/usr/bin/perl
use warnings;
use strict;
use IO::File;

my $cdbmakecmd = '/usr/local/bin/cdbmake';
my $home = exists $ENV{HOME} ? $ENV{HOME} : '';
my $data_dir = $home . '/etc/fortune';
my $fortfile = 'sigs-full';

if (scalar @ARGV) {
	die "Usage: $0 [fortunes-file]\n" if @ARGV > 1;
	$fortfile = $ARGV[0];
}

if (index($fortfile, '/') == -1) {
	$fortfile = $data_dir . '/' . $fortfile;
}

my $cdbfile = $fortfile . '.cdb';

my $fhi = new IO::File $fortfile, '<' or die "Can't readopen($fortfile): $!\n";

my @fortunes;
my @lengths;

my $thisfortune = '';

while (<$fhi>) {
	if (/^%$/) {
		my $l = length $thisfortune;
		if ($l > 0) {
			push @fortunes, $thisfortune;
			push @lengths, $l;
		}
		$thisfortune = '';
	} else {
		$thisfortune .= $_;
	}
}
if (length $thisfortune > 0) {
	push @fortunes, $thisfortune;
	push @lengths, length $thisfortune;
}
close $fhi;

if (exists $ENV{'DEBUG'}) {
	open(CDBMAKE, ">&STDOUT");
} else {
	my $pid = open(CDBMAKE, "|-");
	die "$0: Can't fork: $!\n" unless defined $pid;

	if (not $pid) { # child
# Assume djb can create temporary files safely; we shouldn't be creating
# these in vulnerable directories anyway.
		exec {$cdbmakecmd} ($cdbmakecmd,
		    $cdbfile, $cdbfile . $$) or
			die "$0: Exec of '${cdbmakecmd}' failed: $!\n";
	}
}

my $numfort = scalar @fortunes;
my $nl = length("$numfort");
print CDBMAKE "+5,${nl}:count->$numfort\n";

for (my $i = 0; $i < $numfort; ++$i) {
	print CDBMAKE '+' . length("$i") . ',' . $lengths[$i] . ':' .
		"$i" . '->' . $fortunes[$i] . "\n";
}
print CDBMAKE "\n";

close(CDBMAKE) unless exists $ENV{'DEBUG'};

if ($? != 0) {
	my ($ex, $sig, $core) = ($? >> 8, $? & 127, $? & 128);
	my $msg = "$0: $cdbmakecmd died";
	$msg .= ", exitting $ex"        if $ex;
	$msg .= ", signal $sig"         if $sig;
	$msg .= ' (core dumped)'        if $core;
	die $msg . "\n";
}

exit 0;
