#!/bin/bash -e

# run this script from the project root using `./scripts/build_docs.sh`

usage() {
  echo "Usage: $0 [-b]"
  echo ""
  echo "Build Captum documentation."
  echo ""
  echo "  -b   Build static version of documentation (otherwise start server)"
  echo ""
  exit 1
}

BUILD_STATIC=false

while getopts 'hb' flag; do
  case "${flag}" in
    h)
      usage
      ;;
    b)
      BUILD_STATIC=true
      ;;
    *)
      usage
      ;;
  esac
done

echo "-----------------------------------"
echo "Generating API reference via Sphinx"
echo "-----------------------------------"
cd sphinx || exit
make html
cd .. || exit

# run script to parse html generated by sphinx
echo "--------------------------------------------"
echo "Parsing Sphinx docs and moving to Website"
echo "--------------------------------------------"
mkdir -p "website/pages/api/"

cwd=$(pwd)
python scripts/parse_sphinx.py -i "${cwd}/sphinx/build/html/" -o "${cwd}/website/pages/api/"

SPHINX_STATIC_DIR='sphinx/build/html/_static/'
WEBSITE_SPHINX_DIR='website/static/_sphinx/'

mkdir -p $WEBSITE_SPHINX_DIR

# move static files from /sphinx/build/html/_static/*:
for sphinx_static_file in 'documentation_options.js' \
               'doctools.js' \
               'language_data.js' \
               'searchtools.js' \
               'katex_autorenderer.js' \
               'pygments.css' \
               'katex-math.css'
do
  cp "${SPHINX_STATIC_DIR}${sphinx_static_file}" "${WEBSITE_SPHINX_DIR}${sphinx_static_file}"
done

# searchindex.js is not static util
cp "sphinx/build/html/searchindex.js" "${WEBSITE_SPHINX_DIR}searchindex.js"

echo "-----------------------------------"
echo "Generating tutorials"
echo "-----------------------------------"
mkdir -p "website/_tutorials"
mkdir -p "website/static/files"
python scripts/parse_tutorials.py -w "${cwd}"

echo "-----------------------------------"
echo "Install Website dependencies"
echo "-----------------------------------"
cd website || exit
yarn

if [[ $BUILD_STATIC == true ]]; then
  echo "-----------------------------------"
  echo "Building static site"
  echo "-----------------------------------"
  yarn build
else
  echo "-----------------------------------"
  echo "Starting local server"
  echo "-----------------------------------"
  yarn start
fi
