#!/usr/bin/env sh
function err {
echo "$@" >&2
}
if [ $# -ne 1 ]; then
err "./gmi2html.sh /path/to/gmi"
exit 1;
fi
# main method
GMI=$1
list=0
pre=0
quote=0
while read line; do
# if in pre-mode and not closing - print and skip
if [ $pre -eq 1 ]; then
if [ ! -n "$(sed -nE '/^[`]{3}/p' <<< $line)" ]; then
echo "$line"
continue;
fi
fi
# quotes
if [ -n "$(sed -nE '/^[>] .+/p' <<< $line)" ]; then
if [ $quote -eq 0 ]; then
echo ""
fi
quote=1;
text=$(sed -E 's/^[>] (.+)$/\1/g' <<< $line)
echo "$text
"
continue
else
if [ $quote -eq 1 ]; then
if [ -z "$(sed -E '/^[#`*]/d' <<< $line)" ]; then
echo " "
quote=0
fi
fi
fi
if [ -n "$(sed -nE '/^[`]{3}/p' <<< $line)" ]; then
if [ $pre -eq 0 ]; then
echo "
"
pre=1
else
echo " "
pre=0
fi
continue;
fi
# lists
if [ -n "$(sed -nE '/^[*] .+/p' <<< "$line")" ]; then
if [ $list -eq 0 ]; then
echo ""
fi
list=1;
text=$(sed -E 's/^[*] (.+)$/\1/g' <<< "$line")
echo "${text} "
continue
else
if [ $list -eq 1 ]; then
echo " "
fi
list=0;
fi
# single line modifiers
if [ -n "$(sed -nE '/^# .+/p' <<< $line)" ]; then
text=$(sed -E 's/^# (.+)$/\1/g' <<< $line)
echo "$text "
continue
fi
if [ -n "$(sed -nE '/^## .+/p' <<< $line)" ]; then
text=$(sed -E 's/^## (.+)$/\1/g' <<< $line)
echo "$text "
continue
fi
if [ -n "$(sed -nE '/^### .+/p' <<< $line)" ]; then
text=$(sed -E 's/^### (.+)$/\1/g' <<< $line)
echo "$text "
continue
fi
if [ -n "$(sed -nE '/^=> .+/p' <<< "$line")" ]; then
href=$(sed -E 's/^=> ([^ ]+)([ ]?.*)/\1/g' <<< "$line")
if [ -n "$(sed -nE '/^=> [^ ]+ .+$/p' <<< "$line")" ]; then
text=$(sed -E 's/^=> [^ ]+ (.+)$/\1/g' <<< "$line")
else
text=$href
fi
if [ $quote -eq 1 ]; then
echo "— $text "
else
echo "$text
"
fi
continue
fi
# skip blank lines
if [ -z "$line" ]; then
continue
fi
# default paragraphs
if [ $quote -eq 1 ]; then
echo "— $line "
else
echo "$line
"
fi
done < $GMI