#!/bin/bash # Patch mdbook theme to add language selector and utility links # Usage: patch-mdbook-theme.sh set -euo pipefail DOCS_DIR="${1:?Usage: $0 }" L10N_DIR="${2:?Usage: $0 }" HEAD_HBS="$DOCS_DIR/theme/head.hbs" # Convert FTL locale code to URL code: strip region when language == region # (e.g., fr-FR -> fr, es-ES -> es) but keep distinct ones (zh-Hans, pt-BR, nb-NO) ftl_to_url() { local code="$1" local lang="${code%%-*}" local region="${code#*-}" # If region is the language uppercased (fr-FR, es-ES, etc.), simplify to just the language if [ "${region,,}" = "${lang,,}" ]; then echo "$lang" else echo "$code" fi } # Generate display name for a locale code # Uses python3+babel if available, otherwise falls back to the code itself locale_display_name() { local code="$1" if command -v python3 > /dev/null 2>&1; then local name name=$(python3 -c " try: from babel import Locale print(Locale.parse('${code}'.replace('-', '_')).get_display_name()) except Exception: print('${code}') " 2>/dev/null) # Capitalize first letter for consistency echo "${name^}" else echo "$code" fi } # Scan l10n repo to find which locales have translations # Use a representative utility (ls) to find available locales LANGS_JSON="['en', 'English']" for ftl in "$L10N_DIR"/src/uu/ls/locales/*.ftl; do [ -f "$ftl" ] || continue ftl_name=$(basename "$ftl" .ftl) [ "$ftl_name" = "en-US" ] && continue url_code=$(ftl_to_url "$ftl_name") display=$(locale_display_name "$ftl_name") LANGS_JSON="$LANGS_JSON, ['$url_code', '$display']" done # Append styles and JS to head.hbs cat >> "$HEAD_HBS" << 'ENDSTYLE' ENDSTYLE cat >> "$HEAD_HBS" << 'ENDSCRIPT' ENDSCRIPT # Inject the dynamically-built language list and generation date GENDATE=$(date -u +%Y-%m-%dT%H:%M:%SZ) sed -i "s|LANGS_PLACEHOLDER|[${LANGS_JSON}]|" "$HEAD_HBS" sed -i "s|GENDATE_PLACEHOLDER|'${GENDATE}'|" "$HEAD_HBS" echo "Patched $HEAD_HBS with language selector and utility links"