#!/bin/sh

# Lizenz: CC0
# https://creativecommons.org/publicdomain/zero/1.0/deed.de
# SPDX-License-Identifier: CC0-1.0

# benoetigt: markdown
# einbinden mit "--Erweiterung md=/cgi-bin/md"

DATEI="${PATH_TRANSLATED}"
CACHE="Cache-Control: public, max-age=86400"

if [ ! -r "${DATEI}" ]
then
  echo "Status: 404 Not Found"
  echo "Content-Type: text/plain; charset=UTF-8"
  echo
  test "${REQUEST_METHOD}" = "HEAD" || echo "* Not Found: ${PATH_INFO}"
  exit 1
fi

NAME="${PATH_INFO##*/}"
NAME="${NAME%.*}"

case "$1" in
  (md|markdown)
    echo "Content-Type: text/markdown; charset=UTF-8"
    echo "Content-Disposition: inline; filename=\"${NAME}.md\""
    echo "${CACHE}"
    echo
    test "${REQUEST_METHOD}" = "HEAD" || /bin/cat "${DATEI}"
    exit 0 ;;

  (txt|text)
    echo "Content-Type: text/plain; charset=UTF-8"
    echo "Content-Disposition: inline; filename=\"${NAME}.txt\""
    echo "${CACHE}"
    echo
    test "${REQUEST_METHOD}" = "HEAD" || /bin/cat "${DATEI}"
    exit 0 ;;
esac

# XHTML
echo "Content-Type: application/xhtml+xml; charset=UTF-8"
echo "Content-Disposition: inline; filename=\"${NAME}.xhtml\""
echo "${CACHE}"
echo

test "${REQUEST_METHOD}" = "HEAD" && exit 0

/bin/cat <<EOT
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.1//EN'
  'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>${NAME}</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style type="text/css">
body {
  font-family: "URW Palladio L",Palatino,serif;
  line-height:1.5;
  max-width:35em;
  padding:1ex;
  margin:2ex auto;
}
div.nav{text-align:right;font-size:medium}
@media screen and (prefers-color-scheme:light){
  html{color:#000;background-color:#653}
  body{color:#000;background-color:#F4ECD8}
  h1,h2,h3,h4,h5,h6 {color:#8B4513}
}
@media screen and (prefers-color-scheme:dark){
  html{color:#D2B48C;background-color:#000}
  body{color:#D2B48C;background-color:#210;border:solid thin #653}
  h1,h2,h3,h4,h5,h6 {color:#FF7}
}
@media screen and (min-width: 1024px) {
  body{font-size:x-large;padding:3em !important}
}
@media print { div.nav{display:none} }
p{text-align:justify;}
a{color:inherit}
blockquote {padding-left: 1em; border-left: thick solid gray}
hr{border: medium dashed gray}
</style>
</head>

<body>
<div class="nav">
&#x1F4C2; <a href=".">Dir</a> &#x2022;
&#x1F3E0; <a href="/">Start</a> &#x2022;
&#x1F4DC; <a href="?markdown">Markdown</a>
</div>

<div id="main">
EOT

markdown "${DATEI}"

echo "</div></body></html>"
