#! /usr/bin/env perl

# mdn - a simple web page generator. Call like this: 
#
# % Markdown.pl file.md | mdn > file.html
# 
# Typical Makefile:
#
# .SUFFIXES: .html .mdu
# 
# .mdu.html: 
#	Markdown.pl $< | mdn -s http://hack.org/mc/nav.css -n /mc/nav.html > $@
#
#
# Copyright (c) 2014 Michael Cardell Widerkrantz <mc@hack.org>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
# WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
# AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
# DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
# PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
# TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.

use strict;
use warnings;
use Getopt::Std;

# Stylesheet URL. Set with -s.
my $stylesheet = "";

# Navigation bar include. Set with -n.
my $nav = "";

my %opts;

getopts("n:s:", \%opts);

if ($opts{'s'}) {
    $stylesheet = $opts{'s'};
}

if ($opts{'n'}) {
    $nav = $opts{'n'};
}

print '<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
';

if ($stylesheet)
{
    print "<link rel=\"stylesheet\" type=\"text/css\" href=\"$stylesheet\">\n";
}

my $title = "";

my $first = 1;
my $pre = 0;
while (<>)
{
    if ($first)
    {
	# This is the first line. Remove the paragraph tags and use it as
	# the title.
	s/<p>//;
	s/<\/p>//;
	$first = 0;

	$title = $_;
        chomp $title; # Get rid of newline
            
	print "<title>${title}</title>\n</head>\n<body>\n";

        if ($nav) {
            #print "<!--# include file=\"$nav\" -->\n";
            #print "{{ include \"$nav\" }} \n";

            print "<nav>\n";
            print "<a href=\"/~mc/\">Home</a> | ";
            print "<a href=\"/~mc/bio.html\">About</a> | ";
            print "<a href=\"/~mc/now.html\">Now</a> | ";
            print "<a href=\"/~mc/writings.html\">Writings</a> | ";
            print "<a href=\"/~mc/blog/\">Blog</a> | ";
            print "<a href=\"/~mc/projects/\">Projects</a> | ";
            print "<a href=\"/~mc/contact.html\">Contact</a>";
            print "</nav>";
        }

	print "<h1>${title}</h1>\n";
    }
    elsif (m/<pre>/)
    {
        $pre = 1;
        print;
    }
    elsif (m#</pre>#)
    {
        $pre = 0;
        print;
    }
    elsif ($pre)
    {
	print;
    }
    elsif (!$pre && $_ !~ /^;/ && $_ !~ /^<p>;/)
    {
        print;
    }
}

print "\n</body>\n</html>\n";
