#!/bin/bash
# source in some common functions
. common.sh
PROG_NAME="=== build-docs ==="
USAGE=$(
cat <<EOF
$PROG_NAME
Run the set of Sphinx commands to build both HTML and PDF documentation
 and then copy the PDF out of the build directory to ./resources/pdf

USAGE: $0 [flags] <repo_root>
EOF
)
. shflags

# configure shflags
DEFINE_boolean \
    'clean' \
    "false" \
    'Perform a make clean before building the documentation' \
    'c'

FLAGS_HELP="$USAGE"

# parse the command-line
FLAGS "$@" || exit $?
eval set -- "${FLAGS_ARGV}"

# Make sure the root directory is set
if [[ -z "$1" ]]; then
  echo "[error] no repo root defined" 2>&1
  exit 1
fi

# exit on error and undef not allowed
set -eu

ROOT_DIR=$(readlink -f "$1")
echo "$PROG_NAME"
echo "[info] repo root: $ROOT_DIR"

# Make sure all the expected files and dirs are available
# **** this also sets a load of variables that will be used below ****
check_repo "$ROOT_DIR"

# First we copy the README over to the docs and update the paths
# to it's new location
# sphinx source and main readme are defined by check_repo
getting_started="$sphinx_source"/getting_started.md
cp "$main_readme" "$getting_started"
sed -i 's/\.\/docs\/source\///' "$getting_started"
sed -i 's|src="\./resources/images|src="./_static/images|'  "$getting_started"

## If we want to clean then do so
if [[ "$FLAGS_clean" -eq 0 ]]; then
  echo "[info] cleaning old files"
  make --directory "$sphinx_docs" clean
fi

make --directory "$sphinx_docs" html

echo "Press <ENTER> to build PDF [CTRL-C to quit]..."
read var

make --directory "$sphinx_docs" latexpdf

echo "[info] copy PDF..."
mkdir -p "$resources_dir"/pdf/
cp "$sphinx_build"/latex/*.pdf "$resources_dir"/pdf/

## Have to manually copy the image files??
#rsync -avz ../resources/diagrams/* ./build/html/_static/images/
#cd "$cur_dir"
#
## Have to manually copy the image files??
## rsync -avz ../resources/diagrams/* ../../../docs/build/html/_static/images/

echo "*** END ***"
