#! /bin/bash
# -*- tab-width: 4; -*-
# vi: set sw=2 ts=4:textwidth=70

# Copyright 2016-2020 Mark Callow
# SPDX-License-Identifier: Apache-2.0

# Run doxygen, creating any requested output directory first.
# This script is needed because (a) Doxygen refuses to create
# more than one level of directory and (b) there is no way to
# chain commands together in GYP actions. Even were (a) fixed,
# we'd still need this to set the timestamp file.

# Doxygen must be run in the top-level project directory
# so that ancestors of that directory will be removed
# from paths displayed in the documentation. That is also
# the directory where the .doxy and .gyp files are stored.

function usage() {
  echo "Usage: $0 [[-o <output>] ...] [-t <timestampfile>] <doxyFile>"
  exit 1
}

doxygen=$(which doxygen)
if [ $? != 0 ]
then
  if [ `uname` == "Darwin" ]
  then
    # It seems to be inpossible to modify the $PATH variable used for builds
    # run from the Xcode GUI and difficult when running from the command line.
    # Furthermore actions in Xcode are run by 'sh'
    # which does not read startup (.bash_profile etc) files. Check for
    # Doxygen in the standard installation locations including those of
    # MacPorts and Homebrew.
    for i in /Applications/Doxygen.app/Contents/Resources/doxygen \
             /usr/local/bin/doxygen \
             /opt/local/bin/doxygen
    do
      if [ -e $i ]
      then
        doxygen=$i
        break
      fi
    done
    if [ -z "$doxygen" ]
    then
      echo "Doxygen not found in Applications, /opt/local/bin or /usr/local/bin"
    fi
  fi
  if [ -z "$doxygen" ]
  then
    echo "Doxygen not found anywhere on $PATH"
    exit 1
  fi
fi

# XXX Use shell builtin getopts instead....
args=$(getopt o:t: $*)
if [ $? != 0 ]
then
  usage
fi

timestamp=
set -- $args
for i
do
  case "$i" in
    -o) mkdir -p $2 ; if [ $? != 0 ]; then exit 1; fi ;
        shift; shift ;;
    -t) timestamp=$2 ; shift ;
        shift ;;
    --) shift; break;;
  esac
done

if [ $# != 1 ]
then
  usage
fi

"$doxygen" $1
if [ $? != 0 ]
then
  exit 2
fi

if [ -n "$timestamp" ]
then
  touch "$timestamp"
  if [ $? != 0 ]
  then
    exit 3
  fi
fi
