#!/bin/bash

set -e

OPEN_PDF=0

while [ -n "$1" ]
do
   case $1 in
        "--open_pdf" )
            OPEN_PDF=1
            ;;

        "-h" | "--help")
            echo "Usage: $0"
            exit 0
            ;;

        "--verbose")
            set -x
            ;;
        *)
            echo "Unknown param : $1"
            exit 255
            ;;
   esac
   shift
done

OUTPUT_DIR_PDF="docs/autogenerated/"

# Generate in pdf
rm -rf $OUTPUT_DIR_PDF
mkdir -p $OUTPUT_DIR_PDF
poetry run pdoc3 --pdf src.concrete.ml > tmp.pdoc.output.txt 2>/dev/null

# Problems of version
PANDOC_VERSION_IS_NOT_2=$(pandoc --version | grep "pandoc 2." > /dev/null; echo $?)

if [ "$PANDOC_VERSION_IS_NOT_2" -eq 0 ]
then
  ENGINE="--pdf-engine"
else
  ENGINE="--latex-engine"
fi

pandoc --metadata=title:"Concrete ML API Documentation"                 \
       --toc --toc-depth=4 --from=markdown+abbreviations      \
       $ENGINE=xelatex                                        \
       --output=$OUTPUT_DIR_PDF/pdoc.pdf tmp.pdoc.output.txt

rm -f tmp.pdoc.output.txt

echo "Documentation created."
echo "Please open '$OUTPUT_DIR_PDF/pdoc.pdf' for pdf."

if [ $OPEN_PDF -eq 1 ]
then
    open $OUTPUT_DIR_PDF/pdoc.pdf
fi

echo "Successful end"