#! /usr/bin/perl

use warnings;
use strict;

use IO::File;

use User;

my ($temp_file,$quote_file) = @ARGV;
$temp_file  ||= User->Home."/lib/signature_stuff/sigtemplate.txt";
$quote_file ||= User->Home."/lib/signature_stuff/quote.txt";

my $sigfile      = new IO::File User->Home."/.signature", 'w' or die "Unable to open ~/.signature for writing; $!";
my $templatefile = new IO::File $temp_file, 'r' or die "Unable to open $temp_file $!";

local $/;
my $template =<$templatefile>;

undef $templatefile;

my $quote;
my $fortune;
if (-e $quote_file.'.dat' and open($fortune,'-|','fortune',$quote_file)) {
     local $/;
     $quote = <$fortune>;
     close($fortune);
     $quote =~ s/\n$//;
}
else {
     my $quotes = '';
     my $quotesfile   = new IO::File $quote_file,'r' or die "Unable to open $quote_file $!";
     local $/;
     $quotes = <$quotesfile>;
     undef $quotesfile;
     my @quotes = split /\n*\%\n*/s, $quotes;
     undef $quotes;
     my $quote = $quotes[rand(@quotes)];
}


$template =~ s/\[\%\s*quote\s*\%\]/$quote/;

print {$sigfile} $template;

undef $sigfile;
