#!/bin/bash
#
# Copyright (C) 2021 Associated Universities, Inc. Washington DC, USA.
#
# This file is part of NRAO Workspaces.
#
# Workspaces is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Workspaces is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Workspaces.  If not, see <https://www.gnu.org/licenses/>.

# Regenerate the API documentation for the project.
#
# A handy trick in case we build new modules and need to bring them into the documentation system.

# remove the existing source/api folder
rm -rf source/api

# go into the source folder
pushd source

# for each application we have, run sphinx-apidocs
for setup in $(find ../../apps/cli ../../services ../../shared -name setup.py); do
  dir=$(dirname $setup)
  sphinx-apidoc -o api/$(basename $dir) $dir $dir/setup.py $dir/test $dir/tests
done

# generate the header for the API index
cat > api/index.rst <<'EOF'
.. Workspaces documentation master file, created by
   sphinx-quickstart on Thu Oct 15 14:12:32 2020.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

API Documentation
--------------------------------------------

.. toctree::
   :maxdepth: 1

EOF

find . -name \*.bak -delete
find . -name modules.rst | sed 's|\./api/|   |g; s|\.rst||g' >> api/index.rst

cat >> api/index.rst <<EOF
EOF


# generate the architecture API index
cat > architecture.rst <<'EOF'
Architecture
============

The following pages are notes from the ARCHITECTURE.md files.

Contents:

.. toctree::
   :maxdepth: 2

   unlinked_architecture/capability_versions.md
   unlinked_architecture/envoys.md
   unlinked_architecture/restriction_engine.md
   unlinked_architecture/state_machines.md
EOF

# go into the architecture folder
rm -rf architecture
mkdir architecture

pushd architecture
for file in $(find ../../.. -name ARCHITECTURE.md); do
  mdfile=$(basename $(dirname $file)).md
  ln -s $file $mdfile
  echo "   architecture/$mdfile" >> ../architecture.rst
done
popd

popd
