#!/bin/bash

# Defaults for Debian
LYX=lyx

# Sanity checks
if [ ! -d doc/core ]; then
	echo "Can't find usable core documentation structure - aborting"
	exit 1
fi

# Commands present?
for cmd in $CNV $LYX; do
	if [[ ! `which $cmd` ]]; then
		echo "Can't find executable for '$cmd' - aborting"
		exit 2
	fi
done

# Core help
echo -en "Processing core\n"
pushd . &> /dev/null
cd doc/core
for lang in *; do
	[ ! -d "$lang" ] && continue

	pushd . &> /dev/null
	echo -en "\tProcessing language $lang...\n"
	cd $lang/lyx-source

	for source in $(find . -name \*.lyx -exec basename {} \;); do
		echo -en "\t\tProcessing $source..."
		echo -en " pdf"
		$LYX -e pdf $source &> /dev/null
		d=../pdf/${source%%\.*}/
	 	pdf=${source%lyx}pdf
		[ -d $d ] || mkdir -p $d && mv $pdf ../pdf/${source%%\.*}/ &>/dev/null
		d=../html/${source%%\.*}/
		echo -en " done.\n"
	done
	popd &> /dev/null
done

popd &> /dev/null

# Plugin help
pushd . &> /dev/null
if [ -d doc/plugins ]; then
	cd doc/plugins

	for plugin in *; do
		pushd . &> /dev/null
		echo -en "Processing $plugin\n"
		cd $plugin
		for lang in *; do
			[ ! -d "$lang" ] && continue

			pushd . &> /dev/null
			echo -en "\tProcessing language $lang...\n"
			cd $lang/lyx-source

			for source in $(find . -name \*.lyx -exec basename {} \;); do
				echo -en "\t\tProcessing $source..."
				echo -en " pdf"
				$LYX -e pdf $source &> /dev/null
				d=../pdf/${source%%\.*}/
				pdf=${source%lyx}pdf
				[ -d $d ] || mkdir -p $d && mv $pdf ../pdf/${source%%\.*}/ &>/dev/null
				d=../html/${source%%\.*}/
				echo -en " done.\n"
				continue
			done
			popd &> /dev/null
		done
		popd &> /dev/null
	done

fi
popd &> /dev/null
echo
exit 0
