#!/bin/bash
app=$(basename "$0")

VIM=vim

set -e
#set -x

show_help() {
        set +x
        echo "$app <input.c >output.html     # converts .c file to .html" >&2
        echo "$app <filename>...             # converts a bunch of files" >&2
        exit $1
}

transform() {
        in=$1
        out=$2
        safe=$(echo -n $app.$$.$in | tr -c '[a-zA-Z0-9.]' _)
        tmp=/tmp/$safe

        cat $in > $tmp
        if ! [ -s $tmp ] ; then
                rm -f $tmp
                help 0
        fi

        ( umask 077 && cd /tmp && $VIM -u /dev/null -f +"set bg=dark" +"syn on" +"run! syntax/2html.vim" +"wq" +"q" $safe )
        cat $tmp.html | sed "s,<title>.*</title>,<title>$in</title>," > $out
        rm -f $tmp $tmp.html
}

if [ -z "$1" ] ; then
        transform /dev/stdin /dev/stdout
        exit 0
fi

for f in $@ ; do
        case $f in
        --help|-h|-?)
                show_help 0
                ;;
        esac

        if ! [ -f $f ] ; then
                echo "$app: $f is not a file" >&2
                show_help 1
        fi

        transform $f $f.html
done