#!/bin/sh

#
# build-struct - script used in conjuction with Makefile of 'office'
#                Creates directory structure for typeseting Postscript
#                and PDF document from one *.tex file
#
# Usage: ./build-struct <directory>
#
# Developed by Lubomir Host 'rajo' <rajo AT platon.sk>
# Copyright (c) 2003 Platon SDG
# Licensed under terms of GNU General Public License.
# All rights reserved.
#
# Changelog:
# 30/01/2003 - created
#

# $Platon: platos/_scripts/build-struct,v 1.13 2005/09/18 10:27:22 rajo Exp $

usage()
{ # {{{
	echo -e "${RED}Usage:"
	echo
	echo -e "$0 <PostScript|PDF|HTML|RTF> <LATEX|PDFLATEX|LATEX2HTML|LATEX2RTF> <command>${RESET}"
	echo
	exit 1
} # }}}

test_environ()
{ # {{{
	for i in $*; do
		if [ -z "${!i}" ]; then
			echo -e "${RED}Empty ${YELLOW}\$$i${RED}, did you specify it in Makefile and export it?${RESET}"
			exit 1
		fi
	done

} # }}}

make_symlinks()
{ # {{{
	dirname="$1"
	outname="$2"
	in_name="$3"

	inp="${!in_name}"
	
	test -d $dirname || mkdir -p $dirname
	cd $dirname \
		&& (
			ln -s -f "../$outname" "$outname";
			for i in $inp; do
				ln -s -f "../$i" "$i"
			done;
			for i in $DEPEND_all; do
				f="`basename $i`"
				rm -f "$f"
				ln -s -f "../$i" "$f" \
					|| cp "../$i" "$f"
			done
		)
} # }}}

if [ "$#" -lt "3" ]; then
	usage;
fi

test_environ \
	DEPEND_all \
	OUTPUT \
	TOP_DIR

# tests for availability of required commands
# {{{
if [ "X$2" = "X" ]; then
	usage;
fi
if [ "X$3" = "X" ]; then
	echo -e "${RED}Please, specify command $2= in your Makefile${RESET}"
	exit 1
else
	cmd="`which $3`";
	version="`$cmd -v 2>/dev/null | head -n 1`"
	if [ "Bad$version" = "Bad" ]; then
		echo -e "${RED}Command ${YELLOW}$3${RED} returns bad version string, Building of $1 skipped ...${RESET}"
		exit 1;
	fi
fi
# }}}

echo -e "${BLUE}Building ${MAGENTA}$1${BLUE} with ${YELLOW}$cmd${BLUE} version ${YELLOW}$version${RESET}"
# {{{
if [ "X$1" = "XPostScript" ]; then
	
	test_environ ps__INPUT ps__OUTPUT
	make_symlinks PostScript ps__OUTPUT ps__INPUT

elif [ "X$1" = "XPDF" ]; then

	test_environ pdf_INPUT pdf_OUTPUT
	make_symlinks PDF pdf_OUTPUT pdf_INPUT

elif [ "X$1" = "XHTML" ]; then

	test_environ htm_INPUT htm_OUTPUT
	make_symlinks HTML htm_OUTPUT htm_INPUT

elif [ "X$1" = "XRTF" ]; then

	test_environ rtf_INPUT rtf_OUTPUT
	make_symlinks RTF rtf_OUTPUT rtf_INPUT

else
	echo -e "${RED}I don't know, what do you want with parameter '$1'...${RESET}"
	exit 1
fi
#}}}

# vim: fdm=marker fdl=0 fdc=3

