#!/bin/sh
set -e

# Parameters:
mdwn=$1
html=$2

# Usage check:
if [ -z "$mdwn" -o -z "$html" ]; then
    echo "Usage: $0 file.mdwn file.html"
    exit 1
fi

# Sanity check:
if ! which markdown >/dev/null; then
    echo "E: Missing markdown command"
    exit 1
fi

# Remember the title, assume it has no formatting:
title=$(head -1 $mdwn|sed -e 's/^#//')

# Add a link back to the index:
if [ "$mdwn" != "index.mdwn" ]; then
    path=$(dirname $mdwn)/
    if [ "$path" = "./" ]; then
        path_to_root=./
    else
        path_to_root=$(echo $path|sed 's,[^/],,g;s,/,../,g')
    fi
    sed "s,^# ,# [XSF](${path_to_root}index.html) / ," $mdwn > $mdwn.tmp
else
    cp $mdwn $mdwn.tmp
fi

# Actual transformation:
markdown $mdwn.tmp > $html.tmp

# Include html headers, include title:
sed "s#@@title@@#$title#" > $html <<EOF
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>@@title@@</title>
<link rel="stylesheet" type="text/css" href="xsf.css" />
<link rel="stylesheet" type="text/css" href="../xsf.css" />
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
</head>
<body>
EOF

# Actual content
cat $html.tmp >> $html

# Add html footers:
cat >> $html <<EOF
</body>
</html>
EOF

# Remove temporary files:
rm -f $mdwn.tmp $html.tmp
