#!/bin/sh
# $1 - path to working directory
# $2 - out dir

WD=$1
OUT=$2
LOG=$3
# check in
[[ -z $WD || -z $OUT ]] && return 2

# $1 — link addr
# $2 — link name
upln() {
	[[ -L "$2" ]] && rm -f "$2"
	ln -s "$1" "$2"
}

# == Main ==
cd $WD || exit 1

# pulling up
hg pull -u || exit 1
# get revision & tag
Rev="$(hg identify -n):$(hg identify -i)"
Tag="$(hg identify -t)"

# There is no doxygen config
[[ -f $PWD/Doxyfile ]] || (
	echo "No Doxyfile";
	exit 0
)

# exit if we alredy do this doc
[[ -d "$OUT/$Rev" ]] && exit 0

# prepare Doxyfile
Doxyfile=`mktemp ./Doxyfile-tmp.XXXX`
DoxOut=$PWD/doc/doxygen
sed "s/^\(PROJECT_NUMBER.*=.*\)/\1 rev. $Rev/" $PWD/Doxyfile > $Doxyfile

# Clean prevoius build
[[ -d $DoxOut ]] && (
	rm -rf $DoxOut
)

# build
doxygen $Doxyfile || (
	rm -f $Doxyfile;
	exit 3
)

# rm temp Doxyfile
rm -f $Doxyfile

# try to compile pdf doc
[[ -d $DoxOut/latex ]] && (
#	make -C $DoxOut/latex
#	mv $DoxOut/latex/refman.pdf $DoxOut
#	# LaTeX sources not needed
	rm -rf $DoxOut/latex
)

[[ -f $LOG ]] && (
	local rt="$Rev"
	[[ -n $Tag ]] && rt="$rt ($Tag)"
	echo "`date`: Create documentation" \
		" for $WD rev. $rt" >> $LOG
)

# copy work
mkdir "$OUT/$Rev" || exit 4
cp -R $PWD/doc/doxygen/* "$OUT/$Rev" || exit 4

# create tag symlink
[[ -n $Tag ]] && (
	upln "$OUT/$Rev" "$OUT/$Tag"
)

# TODO: Clean old

exit 0

