#!/usr/bin/perl

use warnings;
use strict;

my $recepies = '/srv/sysadmin-cookbook/recepies';

use File::Find;
use File::Slurp;
use Data::Dump qw/dump/;

my @html;
sub html { push @html, @_ }

my %escape = ('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;');
my $escape_re  = join '|' => keys %escape;

sub file {
	my $path = shift;
	my $content = read_file $path;
	$content =~ s{[\n\r\s]+$}{}s;
	$content =~ s/($escape_re)/$escape{$1}/gs;
	return ''
		. "<pre class=changes>" . `svn log $path` . "</pre>"
		. "<pre class=content>$content</pre>"
		;
}

my @names;
find({ follow => 0, no_chdir => 1, wanted => sub {
	push @names, $_ unless m{/\.};
}}, $recepies );

my $last_level = 0;
my $toc_html = '';
sub header {
	my ($level, $content) = @_;
	html qq|<a name=$content></a>|;
	html qq|<h$level>$content</h$level>|;

	if ( $last_level > $level ) {
		$toc_html .= "</ul>";
	} elsif ( $last_level < $level ) {
		$toc_html .= "<ul>";
	}
	$toc_html .= qq|<li><a href="#$content">$content</li>|;
	$last_level = $level;
}

foreach my $path ( sort @names ) {

	my $name = $path;
	$name =~ s{^$recepies.*?([^/]+)$}{$1};
	next unless $name;

	if ( -d $path ) {
		header 1,$name;
	} elsif ( -l $path ) {
		my $to = readlink $path;
		header 2,$name;
		html $to;
	} else {
		header 2, $name;
		html file( $path );
	}

};

$toc_html .= "</ul>" foreach ( 1 .. $last_level );

print qq|
<html><head>
<title>Sysadmin Cookbook</title>
<!--
<link type=text/css rel=stylesheet href="style.css">
-->
<style type=text/css>
pre.changes {
	color: #444;
}
pre.content {
	padding: 1em;
	background: #eee;
}
</style>
</head><body>
	|
	. "<div class=toc>$toc_html</div>"
	, join("\n", @html)
	, "</body></html>"
	;

