#!/bin/bash

# The global generated swh documentation lacks local scoping when browsing subprojects
# documentation. For instance, when browsing the swh-model doc, indices and search are
# scoped to all swh modules which is not really convenient as the reader only wants to
# focus on swh-model.

# This postprocess script is used to copy each swh module indices generated by Sphinx
# into the global swh html documentation tree.
# The script also takes care of fixing the indices references in the generated html files,
# thus pointing to subprojects indices when browsing their dedicated documentation.

# Copy subprojects index files from their standalone documentation to the global swh
# documentation tree anf fix paths to assets once it is done
declare -a index_files=("genindex.html" "py-modindex.html" "search.html" "searchindex.js" "http-routingtable.html")
for pymodule in $(cd ../../ && bin/ls-py-modules) ; do
    if [ "$pymodule" = 'swh-docs' ] ; then
        continue
    fi
    orig_index_path="$pymodule/_build/html"
    cp_index_path="_build/html/$pymodule"
    for index_file in "${index_files[@]}"
    do
        if [ -e "$orig_index_path/$index_file" ] ; then
            cp "$orig_index_path/$index_file" "$cp_index_path/$index_file"
            sed -i 's/_static/\.\.\/_static/g' "$cp_index_path/$index_file"
        fi
    done
done

# Fix some file paths in subprojects documentation for a better navigation.
# When navigating in a subproject doc, we want to get back to its index page
# when clicking on the top left swh logo.
# The only exception is for a subproject doc index page: when clicking on the
# swh logo, we get back to the root doc index.
declare -a file_to_fix_path_in_subproject=("index\.html" "search\.html" "genindex\.html")
for file in "${file_to_fix_path_in_subproject[@]}"
do
    find . -mindepth 4 -maxdepth 4 -name *.html ! -name index.html | xargs sed -i "s/\"\.\.\/$file\"/\"$file\"/g"
    find . -mindepth 5 -maxdepth 5 -name *.html ! -name index.html | xargs sed -i "s/\"\.\.\/\.\.\/$file\"/\"\.\.\/$file\"/g"
done

# Fix paths to subprojects indices. When navigating in a subproject doc
# we want to use indices only scoped to that subproject.
# Global indices and search are still available from the doc root index page
declare -a file_to_fix_path_in_subproject_index=("genindex\.html" "py-modindex\.html" "search\.html")
for file in "${file_to_fix_path_in_subproject_index[@]}"
do
    find . -name index.html | xargs sed -i "s/\"\.\.\/$file\"/\"$file\"/g"
done
# Ensure the root toc link points to each subproject doc index page
find . -name index.html | xargs sed -i 's/"\.\.\/index\.html">Table Of Contents/"index\.html">Table Of Contents/g'
