#! /bin/bash

export TMPDIR=/tmp/$$;

echo "Installed tree: $PREFIX"
echo "using temporary directory: $TMPDIR"

function abort()
{
     /usr/bin/sleep 1; /bin/rm -rf $TMPDIR; exit 1
}

trap 'abort' 1 2 3 6 9 15

# export BINDIR=${BINDIR}
# export DATADIR=${DATADIR}
export PKGDATADIR=${DATADIR}/linuxdoc-tools
export PERL5LIB=${DATADIR}/linuxdoc-tools:${TMPDIR}

mkdir -m 700 $TMPDIR || exit 1;
mkdir $TMPDIR/Text
sed < ../entity-map/EntityMap.pm.in >$TMPDIR/Text/EntityMap.pm \
 -e 's|\@localentitymapdir\@|'${DATADIR}'/entity-map|g' \
 -e 's|\@entitymapdir\@|'${DATADIR}'/entity-map/0.1.0|g'

cp -r ${DATADIR}/linuxdoc-tools $TMPDIR

NSGMLS=`which nsgmls`
SGMLSASP=`which sgmlsasp`
GROFF=`which groff`
GAWK=`which gawk`
PERL=`which perl`

sed < ../bin/linuxdoc.in >$TMPDIR/linuxdoc \
 -e 's!\@prefix\@!'${PREFIX}'!' \
 -e 's!\@BINDIR\@!'${BINDIR}'!' \
 -e 's!\@DATADIR\@!'${TMPDIR}'/linuxdoc-tools!' \
 -e 's!\@NSGMLS\@!'${NSGMLS}'!' \
 -e 's!\@SGMLSASP\@!'${SGMLSASP}'!' \
 -e 's!\@GROFF\@!'${GROFF}'!' \
 -e 's!\@GROFFMACRO\@!-ms!' \
 -e 's!\@AWK\@!'${GAWK}'!' \
 -e 's!\@PERL\@!'${PERL}'!' \
 -e 's!\@PERLWARN\@!!' \
 -e 's!^use lib \".*\/linuxdoc-tools\"!use lib \"'${TMPDIR}'\"!' \
 -e '/^use lib \".*\/usr\/perl5\";/a \
use lib \"/usr/perl5\";
' \
 -e 's/^use lib \".*\/usr\/perl5\";/use lib \"\/usr\/local\/perl5\";/' \
 -e '/^use lib \".*\/lib\/perl5\";/a \
use lib \"/usr/lib/perl5\";
' \
 -e 's/^use lib \".*\/lib\/perl5\";/use lib \"\/usr\/local\/lib\/perl5\";/' \
 -e '/^use lib \".*\/share\/perl5\";/a \
use lib \"/usr/share/perl5\";
' \
 -e 's/^use lib \".*\/share\/perl5\";/use lib \"\/usr\/local\/share\/perl5\";/'

chmod u+x $TMPDIR/linuxdoc

sed -e '/global->{NsgmlsOpts} .= \"-D \/usr\/share\/sgml \"/a \
  $global->{NsgmlsOpts} .= " -c TMPCONFIG"; \
  $global->{NsgmlsOpts} .= " -D TMPLIBDIR1"; \
  $global->{NsgmlsOpts} .= " -D TMPLIBDIR2";
' \
 ${PKGDATADIR}/LinuxDocTools.pm | sed \
  -e "s,TMPCONFIG,"${DATADIR}"/linuxdoc-tools/dtd/catalog ," \
  -e "s,TMPLIBDIR1,"${DATADIR}"/linuxdoc-tools ," \
  -e "s,TMPLIBDIR2,/usr/share/sgml ," \
   >$TMPDIR/linuxdoc-tools/LinuxDocTools.pm

if [ -n "`which groff`" ]; then
	ln -s $TMPDIR/linuxdoc $TMPDIR/sgml2txt
	$TMPDIR/sgml2txt ./guide
fi
if [ -n "`which latex`" ]; then
	ln -s $TMPDIR/linuxdoc $TMPDIR/sgml2latex
	$TMPDIR/sgml2latex -o dvi ./guide
fi
if [ -n "`which dvips`" ]; then
	dvips -t letter -o ./guide.ps ./guide.dvi
	if [ -n "`which gzip`" -a -f ./guide.ps ]; then
		gzip -fN ./guide.ps
	fi
fi


$TMPDIR/linuxdoc -B info ./guide.sgml
$TMPDIR/linuxdoc -B lyx ./guide.sgml

$TMPDIR/linuxdoc -I -B html ./guide && mv -f ./guide*.html ./html

$TMPDIR/linuxdoc -B rtf ./guide && if [ ! -d ./rtf ]; \
 then mkdir -m 755 ./rtf; fi && mv -f ./guide*.rtf ./rtf

rm -rf $TMPDIR

exit 0
