#!/usr/bin/perl

use strict;
use warnings;

use Template;
use Data::Dumper;

my %valid_headers = map {$_ => 1} qw(From Subject Date URL Traffic);

my $save_config_file = "config.cfg";

my $tmpl_file = "story.tmpl";
my $config = {
              INCLUDE_PATH => ".",
              OUTPUT_PATH  => ".",
             };
my $template = Template->new($config) or die $Template::ERROR, "\n";

my %map = (
         '>' => 'E<gt>',
         '<' => 'E<lt>',
         '&' => 'E<amp>',
        );

###############################################################################

my @files = @ARGV ? @ARGV : <*.txt>;

for my $file (@files) {
    (my $pod_file = $file) =~ s/\.txt$/.pod/;
    my $data = process($file);
    generate($pod_file, $data);
}
update_config_file();


sub process {
    my $file = shift;

    open my $fh, $file or die "cannot open $file: $!";
    local $/ = "";
    my $headers = <$fh>;
    local $/;
    my $body = <$fh>;
    close $fh;

    # headers
    my %headers = map {(/(\w+)\s*:\s+(.*)/ && $valid_headers{$1}) ? ($1,$2) : ()} 
        split /\n/, $headers;

    my $title = delete $headers{Subject};
    die "error: no Subject: in $file" unless $title;

    my $author = delete $headers{From};
    die "error: no From: in $file" unless $author;

    # antispam
    $author =~ s/\@/ (at) /;

#    print Dumper \%headers;
#    print "headers:\n$headers\n";
#    print "body:\n$body\n";

    my %data = (
                title   => $title,
                author  => $author,
                headers => \%headers,
               );

    # cleanup for pod
    _encode(\%data);

    # keep the body as is
    $body =~ s/^/  /mg;
    $data{body} = $body;

    return \%data;
}

sub generate {
    my ($filename, $data) = @_;
    print "+++ writing $filename\n";

    #  print Dumper \@search_path;
    my $vars = {story => $data};
    $template->process($tmpl_file, $vars, $filename)
        or die "error: ", $template->error(), "\n";

}

# automatically generate the config file maintain the list of
# available stories, so when new stories are added they will be
# automatically linked on the next rebuild.
sub update_config_file {
    my $code = join ",\n" . " " x 8, map {qq('$_')} <*.pod>;
    local $/;
    my $tmpl = <DATA>;
    $tmpl =~ s/\@CHAPTERS\@/$code/;

    print "+++ generating $save_config_file\n";
    open my $fh, '>', $save_config_file 
        or die "cannot open $save_config_file:$!";
    print $fh $tmpl;
    close $fh;
}

sub encode { 
    $_[0] =~ s/([>&<])/$map{$1}/g;
}
sub _encode {
    my $ref = ref $_[0];
    if (!$ref) {
        encode($_[0]) if defined $_[0];
    } elsif ($ref eq 'ARRAY') {
        _encode($_) for @{$_[0]};
    } elsif ($ref eq 'HASH') {
        _encode($_[0]->{$_}) for keys %{$_[0]};
    } else {
        # nothing
    }
}


__DATA__
# WARNING: this file is autogenerated, DO NOT EDIT IT
# WARNING: edit ./make.pl instead
use vars qw(@c);
@c = (
    id => 'success_stories',

    title => "Success Stories",

    abstract => "Success reports from people using mod_perl",

    body => {
        bot => 'index_bot.html',
    },

    chapters => [
        @CHAPTERS@
    ],
);
1;
