#!/bin/bash

# faust2mathdoc.sh
#
# Generate a full Faust documentation, in a '*-mdoc' top directory.
#
# Karim Barkati
# November 2009
#
#   Warning : this script requires several things to be installed :
# - svg2pdf, from the Cairo 2D graphics library;
# - pdflatex, to compile the tex file;
# - breqn, a latex package to break equations;
# - faust ;-)


# Usage.
print_usage() 
{
    echo "usage: faust2mathdoc [-l LANG] faust_file.dsp ..."
    echo " LANG is usually a 2-lowercase-letters language name, like en, fr, or it."
}


# Visit each directory transmited as argument,
# in order to convert process.svg files into pdf.
# This function uses the svg2pdf command,
# from the Cairo 2D graphics library.
convert_svgprocesses2pdf()
{
    for DIR in $@ ; do
	if [ -d $DIR ] ; then
	    echo "cd " $DIR
	    cd $DIR
	    FILE="process.svg"
	    for SRC in $FILE ; do
		echo ' --> '$SRC
		PDF=${SRC%.svg}'.pdf'
		svg2pdf "$SRC" "$PDF"
		echo ' <-- '$PDF
	    done
	    cd -
	else
	    echo error : \'$DIR\' is not a directory.
	fi
    done
}


# Visit each directory transmited as argument,
# in order to convert .svg files into pdf.
# This function uses the svg2pdf command,
# from the Cairo 2D graphics library.
convert_svgdirs2pdf()
{
    for DIR in $@ ; do
	if [ -d $DIR ] ; then
	    #echo "cd " $DIR
	    cd $DIR
	    FILES=`ls | grep -E "\.svg"`
	    for SRC in $FILES ; do
		#echo ' --> '$SRC
		PDF=${SRC%.svg}'.pdf'
		svg2pdf "$SRC" "$PDF"
		echo "svg2pdf $SRC $PDF"
		#echo ' <-- '$PDF
	    done
	    cd ..
	else
	    echo error : \'$DIR\' is not a directory.
	fi
    done
}

if [ $# -eq 0 ]
then 
    print_usage
    exit 1
fi

MDLANGOPT=""
if [ $1 = "-mdlang" ] || [ $1 = "--mathdoc-lang" ] || [ $1 = "-l" ]
then
    if [ $# -eq 2 ]
    then 
	print_usage
	exit 1
    fi
    MDLANGOPT="-mdlang $2"
    shift 2
fi

#    Main loop of this script :
# 1. Compile `faust --mathdoc` to generate the TeX file and SVG block-diagrams.
# 2. Move to the "${FILEPATH%.dsp}-mdoc" directory created by faust.
# 3. Convert SVG files into PDF files recursively (with svg2pdf).
# 4. Compile pdflatex twice (including the top-level block-diagram).
# 5. Copy some important files where needed.
for FILEPATH in $@ ; do
    if [ -f $FILEPATH ] ; then
	FILENAME=`basename $FILEPATH` &&
	case $FILENAME in
	    *.dsp )  
		faust $MDLANGOPT -o ${FILEPATH%.dsp}.cpp --mathdoc $FILEPATH &&
		cd ${FILEPATH%.dsp}-mdoc/ && 
		cd svg && convert_svgdirs2pdf svg-* && cd .. &&
		cd tex && pdflatex ${FILENAME%.dsp}.tex && pdflatex ${FILENAME%.dsp}.tex && cd .. &&
		mkdir -p pdf && cp tex/${FILENAME%.dsp}.pdf pdf &&
		mkdir -p cpp && mv ../${FILENAME%.dsp}.cpp cpp &&
		cd ..
		;;
	    * )
		echo error : \'$FILENAME\' does not have a \'.dsp\' extension.
		exit 2
		;;
	esac	
    else
	print_usage
	exit 1
    fi
done
exit 0

