#! /usr/bin/env bash

#
# convert_md.sh
#   A simple Bash wrapper to export Markdown files in HTML, PDF, 
#   or TeX, in batch mode.
#
# Time-stamp: <2011-01-20 21:24:21 chl>
#

# Show help
function usage () {
    echo "convert_md.sh [OPTIONS]"
    echo "Options:"
    echo "  -h --html     Convert Markdown to standalone HTML files"
    echo "  -t --tex      Convert Markdown to ConTeX files"
    echo "  -p --pdf      Convert Markdown to PDF files (markdown2pdf)"
    echo "  -s            Used with -t, produce a standalone file"
    echo "  --help        Show this message"
}

# Process command-line arguments
opt_html=0
opt_tex=0
opt_pdf=0
opt_s=0

OPTERR=0
while getopts ":htps-:" opt ; do
    case $opt in
	h ) opt_html=1 ;;
	t ) opt_tex=1 ;;
	p ) opt_pdf=1 ;;
	s ) opt_s=1	;;
	- ) case $OPTARG in
	        html ) opt_html=1 ;;
	        tex  ) opt_tex=1 ;;
	        pdf  ) opt_pdf=1 ;;
	        help ) usage
                       exit 0 ;;
	        *    ) echo "unknown option --$OPTARG"
	               exit 1 ;;
	    esac ;;
        ? ) echo "unknown option -$OPTARG"
	    exit 1 ;;
    esac
done
shift $(($OPTIND - 1))

# Standalone HTML output
if [ "$opt_html" -ne 0 ] ; then
    for file in *.md
    do
	pandoc -s ${file} -o ${file%.*}.html
    done
    exit 0
fi

# Standalone PDF output
if [ "$opt_pdf" -ne 0 ] ; then
    for file in *.md
    do
	markdown2pdf ${file} -o ${file%.*}.pdf
    done
    exit 0
fi

# Standalone or chunked ConTeXt output
if [ "$opt_tex" -ne 0 ] ; then
    for file in *.md
    do
	if [ "$opt_s" -ne 0 ] ; then
	    pandoc -s -w context ${file} -o ${file%.*}.tex
	else
	    pandoc -w context ${file} -o ${file%.*}.tex
	fi
    done
    exit 0
fi
