#!/bin/bash
guidemap=user-guide-modules
enguidedir=../../user-guide/en/xhtml

process_one_lang() {
    ../dump-modules $guidemap.tmp $2 >modules.$1.xml
    xsltproc --stringparam lang $1 -o module-list.$1.html ../modules-web.xsl modules.$1.xml
    xsltproc --stringparam lang $1 -o module-list-nocss.$1.html ../modules-web-nocss.xsl modules.$1.xml
}

enguidedir=$(realpath "$enguidedir")
if test "x$1" == x--list; then
    if test -f "$enguidedir/index.html"; then
        for file in "$enguidedir/"*.html; do
            echo "$file" | sed 's:^.*/::; s/\.html$//'
            grep -E -o "\\<id=([\"'])[a-zA-Z0-9_-]+\\1" "$file" \
                | sed 's/^id=.//; s/.$//' \
                | grep -E -v '^(idm[0-9]|ientry-idm[0-9]|eq-|fig-|table-|gpl-|gfdl-)' \
                | fmt -w 76 \
                | sed 's/^/    /'
        done
        exit 0
    else
        echo "Cannot list links, no guide found in $enguidedir" 1>&2
        exit 1
    fi
fi

if test -f "$enguidedir/index.html"; then
    while read -a xref; do
        module="${xref[0]}"
        if test "$module" = '#'; then
            continue
        fi
        file="$enguidedir/${xref[1]}.html"
        if test -f "$file"; then
            fragment="${xref[2]}"
            if test -n "$fragment"; then
                if grep -E -q -s "\\<id=([\"'])$fragment\\1" "$file"; then
                    : # OK
                else
                    echo "Broken link for $module, fragment $fragment not present in file $file"
                fi
            fi
        else
            echo "Broken link for $module, no such file $file" 1>&2
        fi
    done <$guidemap
else
    echo "Cannot verify links, no guide found in $enguidedir" 1>&2
fi

rm -rf module-lists
mkdir module-lists

pushd module-lists >/dev/null
sed -e '/^#/d' \
    -e '/::/d' \
    -e 's/^\([^\t]\+\)\t\([^\t]\+\)$/\1 \2.html/' \
    -e 's/^\([^\t]\+\)\t\([^\t]\+\)\t\([^\t]\+\)$/\1 \2.html#\3/' \
    ../$guidemap >$guidemap.tmp

process_one_lang en en_US.UTF-8
process_one_lang fr fr_FR.UTF-8
process_one_lang ru ru_RU.UTF-8

rm -rf module-lists/$guidemap.tmp
popd >/dev/null
