#!/usr/bin/env bash

set -E -o nounset -o errexit +o posix -o pipefail
shopt -s inherit_errexit

# This is a script to mangle HTML files generated by JavaDoc (Java 25 EA).
# The JS file for mermaid downloaded from cds.jsdelivr.net doesn't work as of Dec/2024.
# Also, the JavaDoc embeds am info string in a source file with a prefix `language-`, which disturbs the mermaid.min.js script.
# To address this problem, this script does a couple of things.
# 1. It replaces all the occurrences of `class="language-mermaid"` with `class=mermaid`
# 2. It replaces all the occurrences of `../ ... ../mermaid.min.js` with the URL from which it was downloaded originally.
function main() {
  local _target_dir="${1}"
  # Taking care of JavaDoc generated HTML
  find "${_target_dir}" -type f        \
                        -name '*.html' \
                        -exec sed -i -E 's/class=\"language-mermaid\"/class=\"mermaid\"/g' {} \;
  # Taking care of JavaDoc generated HTML
  find "${_target_dir}" -type f        \
                        -name '*.html' \
                        -exec sed -i -E 's!(\.\./)+script-files/mermaid.min.js!https://cdn.jsdelivr.net/npm/mermaid@11.4.1/dist/mermaid.min.js!g' {} \;
  # Taking care of pandoc generated HTML
  find "${_target_dir}" -type f        \
                        -name '*.html' \
                        -exec sed -i -E 's!<pre class=\"mermaid\"><code>!<pre class=\"mermaid\">!g' {} \;
}

main "${@}"
