#!/bin/bash

NAME=ctable
# this script generates NAME's documentation into NAME.pdf
# and then installs (unless the environment variable NOINSTALL is not empty)
# NAME in TEXMFLOCAL
# This is not a make-like process. If you changed any files, then first run
# inst with the --Clean option, then run inst without options.

function die {
  echo -e "$1"
  exit 1
}

LOCAL=`kpsewhich --expand-var '$TEXMFLOCAL'`/tex/latex/$NAME
CLEAN={aux,idx,ilg,chk,fls,ind,log,glo,gls,out,tex}
ALLCLEAN={aux,idx,ilg,chk,fls,ind,log,glo,gls,out,tex,sty,cls,pdf}

function clean {
  eval "rm -f $NAME.$CLEAN doc/*.$CLEAN"
}
function Clean {
  eval "rm -f $NAME.$ALLCLEAN doc/*.$ALLCLEAN"
}

case "$1"
in
-c|--clean) clean; exit;;
-C|--Clean) Clean; exit;;
-h|--help)  echo 'Usage: ./inst [-c|C|h]'; exit;;
?*)         echo 'Illegal argument(s): use -c|-C|-h|--clean|--Clean|--help'; exit;;
esac

echo y |tex $NAME.ins >/dev/null
(
  # recompile example graphics if any is missing:
  cd doc
  ln -sf ../$NAME.sty || exit 1 # use the $NAME.sty version to be installed
  for i in [0-9][0-9]?; do 
    if [ ! -f $i.pdf -o ! -f s$i.pdf ]; then
      echo Creating example graphics
      ./doit || exit 1
      ./doit -c
      break
    fi
  done
  rm $NAME.sty
  cd ..
  
  echo Creating documentation
  pdflatex --recorder --interaction=batchmode $NAME.dtx  || die "`texlog_extract $NAME.log`"
  if [ -f $NAME.glo ]; then
    makeindex -q -s gglo.ist -o $NAME.gls $NAME.glo || echo makeindex-error
  fi
  if [ -f $NAME.idx ]; then
    makeindex -q -s gind.ist -o $NAME.ind $NAME.idx || exit 1
  fi
  pdflatex --recorder --interaction=nonstopmode $NAME.dtx > /dev/null || exit 1
  
  # set environment variable NOINSTALL to skip installation in your textree
  if [ "$NOINSTALL" = "" ]; then
    echo Installing $NAME.{dtx,sty,pdf}
    rm -rf $LOCAL
    mkdir -p $LOCAL
    cp $NAME.{dtx,sty,pdf} $LOCAL || exit 1
  fi
  sudo -i mktexlsr $LOCAL
  exit 0
)
if [ $? != 0 ]; then 
  echo errors detected, see $NAME.log
else
  echo $NAME successfully installed
fi
texlog_extract $NAME

# $Id: inst,v 1.28 2012/05/28 12:53:17 wybo Exp $

