#!/usr/bin/env bash

#!/bin/sh
if [ "$#" -le 0 ]; then
  echo "Usage: $0 input_file(s)" >&2
  exit 1
fi
    
INPUT="$@"

P=`pwd`

# basename $0
C="$0"
C=`dirname "$C"`
C=`ls -d1 "$C"`

TARGET_FILE="$C"

cd `dirname "$TARGET_FILE"`
TARGET_FILE=`basename "$TARGET_FILE"`

# Iterate down a (possible) chain of symlinks
while [ -L "$TARGET_FILE" ]
do
    TARGET_FILE=`readlink "$TARGET_FILE"`
    cd `dirname "$TARGET_FILE"`
    TARGET_FILE=`basename "$TARGET_FILE"`
done

SRCDIR=`pwd -P`
SRCDIR="$SRCDIR/$TARGET_FILE"
# echo $SRCDIR

   
if [ -z "$DOXYGEN" ]; then
	DOXYGEN=`which doxygen`
	
	if [ $? -ne 0 ]; then
	        echo Please add 'doxygen' to your PATH
		exit 1
	fi
	
	export DOXYGEN
fi

if [ ! -x "$DOXYGEN" ]; then
	echo Please make "$DOXYGEN" - executable!;
	exit 1; 
fi

if [ -z "$DOXYGEN_CONFIG" ]; then
	export DOXYGEN_CONFIG="$SRCDIR/dox/Doxyfile.in1"
fi
	
if [ ! -r "$DOXYGEN_CONFIG" ]; then
	echo Please make the doxygen configuration readable: "$DOXYGEN_CONFIG"!;
	exit 1; 
fi

cd "$P"

INPUTTXT=`echo "$INPUT" | sed -e 's@[ :]@_@g' -e 's@[\\\/]@__@g'`

OUTPUT="./DOXY.$INPUTTXT"
# `mktemp -d -q "./DOXY.$INPUTTXT.XXX"`
#if [ $? -ne 0 ]; then
#    echo "$0: Can't create temp dir name, exiting..."
#    exit 1
#fi

if [ -d "$OUTPUT" ]; then
    echo "Directory '$OUTPUT' exists! Deleting..."
    rm -Rf "$OUTPUT/*"
else
    mkdir -p "$OUTPUT/"
fi

export OUTPUT

export INPUT

export GENERATE_HTML=YES GENERATE_LATEX=YES GENERATE_RTF=YES GENERATE_MAN=YES GENERATE_XML=YES \
       HTML_OUTPUT=htm  LATEX_OUTPUT=tex   RTF_OUTPUT=rtf   MAN_OUTPUT=man   XML_OUTPUT=xml 

export abs_top_srcdir="$SRCDIR" abs_top_builddir="$SRCDIR"

echo Running "$DOXYGEN" "$DOXYGEN_CONFIG" with a bunch of exported variables

$DOXYGEN $DOXYGEN_CONFIG

echo Result for "$INPUT" is in "[$OUTPUT/]", under "[$P/]"...
