#! /bin/bash
#
#  Generate Doxygen for Head
#

#
#  Checks the status returned by executables and exits if it is non-zero.
#
check_fatal()
{
  if [ $1 -eq 0 ] ; then
    return
  fi
  shift
  echo "ERROR: $*" >&2
  exit $?
}

usage()
{
  echo "$0: arguments"
  echo "  where arguments are:"
  echo "    -r directory           RTEMS source directory (default=rtems)"
  echo "    -o directory           output source directory"
  echo "    -v                     disable verbose mode"
}

toggle()
{
  if [ $1 = "no" ] ; then
    echo "yes"
    return
  fi
  echo "no"
}

BASE=`pwd`
rtemsdir="${BASE}/rtems"
outdir="not_set"
verbose="yes"

while getopts r:o:v OPT
do
  case "$OPT" in
    r) rtemsdir="${OPTARG}" ;;
    o) outdir="${OPTARG}" ;;
    v) verbose=`toggle ${verbose}` ;;
    *) usage ; exit 1 ;;
  esac
done

test ${rtemsdir} != "not_set"
check_fatal $? "RTEMS directory was not specified"

test ${outdir} != "not_set"
check_fatal $? "Output directory was not specified"

test -d ${rtemsdir}
check_fatal $? "${rtemsdir} does not exist"

test -r ${rtemsdir}/LICENSE.RPCXDR
check_fatal $? "${rtemsdir} does not appear to be RTEMS source"

test -r ${rtemsdir}/configure
check_fatal $? "RTEMS not bootstrapped"

test -d ${outdir}
check_fatal $? "output directory (${outdir}) does not exist"

if [ ${verbose} = "yes" ] ; then
  echo "RTEMS Source:  ${rtemsdir}"
  echo "HTML Location: ${outdir}"
  echo "Doxygen Log:   ${outdir}/doxy.log"
fi

rm -rf b-doc
mkdir b-doc
cd b-doc


test ${verbose} = "yes" && echo "RTEMS - configure"
${rtemsdir}/configure --target=sparc-rtems4.11 --enable-rtemsbsp=sis \
  --disable-networking --disable-tests >c.log 2>&1

test ${verbose} = "yes" && echo "RTEMS - make preinstall"
make -j3 preinstall >b.log 2>&1
cd sparc-rtems4.11/c/sis/cpukit

#mv Doxyfile Doxyfile.tmp
sed -e "s,^OUTPUT_DIRECTORY.*=.*$,OUTPUT_DIRECTORY = ${outdir}," \
    -e "s,^STRIP_FROM_PATH.*=.*$,STRIP_FROM_PATH = ," \
    -e "s,^INPUT.*=.*lib.*$,INPUT = ," \
  <Doxyfile >../../../sis/lib/include/Doxyfile

cd ../../../sis/lib/include

test ${verbose} = "yes" && echo "RTEMS - run Doxygen"
doxygen >${outdir}/doxy.log 2>&1
check_fatal $? "Doxygen build failed - see ${outdir}/doxy.log for details"

exit 0

