#!/bin/bash
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

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

usage() {
  echo "Usage: $0 [-b] [-o]"
  echo ""
  echo "Build MMF documentation. Must be executed from root of MMF repository."
  echo ""
  echo "  -b   Build static version of documentation (otherwise start server)."
  echo "  -o   Only Docusaurus (skip Sphinx, tutorials). Useful when just make change to Docusaurus settings."
  echo "  -p   Port for starting docusaurus build."
  echo ""
  exit 1
}

BUILD_STATIC=false
ONLY_DOCUSAURUS=false
PORT=3000

while getopts 'bhop:' flag; do
  case "${flag}" in
    b)
      BUILD_STATIC=true
      ;;
    h)
      usage
      ;;
    o)
      ONLY_DOCUSAURUS=true
      ;;
    p)
      PORT=${OPTARG}
      ;;
    *)
      usage
      ;;
  esac
done

if [[ $ONLY_DOCUSAURUS == false ]]; then
  echo "-----------------------------------"
  echo "Generating API reference via Sphinx"
  echo "-----------------------------------"
  cd docs || exit
  rm -rf build
  make html
  cd .. || exit
fi

echo "-----------------------------------"
echo "Getting Docusaurus deps"
echo "-----------------------------------"
cd website || exit
yarn

if [[ $ONLY_DOCUSAURUS == false ]]; then
  # run script to parse html generated by sphinx
  echo "--------------------------------------------"
  echo "Parsing Sphinx docs and moving to Docusaurus"
  echo "--------------------------------------------"
  cd ..
  cwd=$(pwd)
  
  rm -r "${cwd}/website/static/api"
  mkdir -p "${cwd}/website/static/api/"

  cp -R "${cwd}/docs/build/html/." "${cwd}/website/static/api/"

#   python scripts/parse_tutorials.py -w "${cwd}"

  cd website || exit
fi  # end of not only Docusaurus block

if [[ $BUILD_STATIC == true ]]; then
  echo "-----------------------------------"
  echo "Building static site"
  echo "-----------------------------------"
  yarn build
  cd ..
else
  echo "-----------------------------------"
  echo "Starting local server"
  echo "-----------------------------------"
  yarn start -p ${PORT}
fi