#!/bin/bash

PREFIX="$HOME/.local"
INSTALL="no"

set -e

# Run from this directory
cd ${0%/*}

# Check dependencies
if [[ ! $(command -v doxygen) ]]; then
   echo "Error: doxygen is not installed." >&2
   exit 1
fi
if [[ ! $(command -v dot) ]]; then
   echo "Error: graphviz is not installed." >&2
   exit 1
fi

# Parse options
for option in "$@"
do
   case $option in
      --prefix=*                       ) PREFIX="${option#*=}" ;;
      --install=*                      ) INSTALL="${option#*=}" ;;
   esac
done

# Remove existing html/ directory which may contain old files
rm -rf ./html/

# Assemble environment variables which are used in the Doxyfile
if [[ "$CI_COMMIT_REF_NAME" == "" ]]; then
   # The following works only with newer versions of git, not in 2.19.1 for example
   #_branch=$(git branch --show-current)
   _branch=$(git rev-parse --abbrev-ref HEAD)
else
   _branch="$CI_COMMIT_REF_NAME"
fi
#PROJECT_NUMBER="version $_branch:$(git log -1 --format="%h (%cd)")"
PROJECT_NUMBER="version $_branch:$(git rev-parse --short HEAD)"

# Generate documentation
PROJECT_NUMBER="$PROJECT_NUMBER" doxygen
cp output_snippets/*png html

# Install
if [[ "$INSTALL" == "yes" ]]; then
   mkdir -p "$PREFIX/share/doc/"
   # Remove existing files under the prefix
   if [[ -d "$PREFIX/share/doc/tnl" ]]; then
      rm -rf "$PREFIX/share/doc/tnl"
   fi
   cp -r ./html/ "$PREFIX/share/doc/tnl"
fi
