#!/bin/sh
# Apply British spellcheck to HTML file on stdin or as arguments.
# With a single filename argument, SPELLEX exceptions are applied.
# Uses en_GB and EOU custom dictionaries.
# Removes all top-level <pre> blocks.
# Removes all top-level <blockquote> blocks.
# Removes all in-line <code> blocks.
# Removes all in-line <q> blocks.
# Removes all in-line [[ID]] citations.

# Find all possibly mis-spelled words and issue as readable info.
WORDS=`cat "$@" |
    sed '/^ *<pre[> ]/,/^ *<\/pre>/d;/^ *<blockquote[> ]/,/^ *<\/blockquote>/d' | \
    sed -e 's/<code>[^<]*<\/code>//g' -e 's/<q>[^<]*<\/q>//g' -e 's/[[a-zA-Z0-9_:-]*]]//g' | \
    hunspell -d en_GB -p script/spellbEOUdict.txt -H -l | \
    sort -u`
echo $WORDS | fmt -60 | awk '{print "INFO: spell: "$0}'

# Bad words are full list minus those containing digits or uppercase.
BADWORDS="`echo $WORDS | fmt -1 | egrep -v '[0-9A-Z]' | fmt -2500`"

# With a single filename argument, SPELLEX exceptions are applied.
# Remove all exceptions from bad words list.
if [ 1 = "$#" ]; then
    INPUTFILE="$1"
    SPELLEXFILE="$INPUTFILE"
    SPELLEX="`sed<$SPELLEXFILE -n -e 's/^<!-- *SPELLEX  *\(.*\)  *--> *$/\1/p'`"
    if [ "" != "$SPELLEX" ]; then
        echo "INFO: SPELLEX: $SPELLEX"
        # Remove all the SPELLEX exceptions from the 'bad' words list.
        STILLBAD=`(echo $BADWORDS; echo $SPELLEX) | \
            awk '
                NR==1{for(i=1;i<=NF;++i){bad[$i]=$i}}
                NR==2{for(i=1;i<=NF;++i){delete bad[$i]};}
                END{for(i in bad){print bad[i]}}
                ' | \
                sort -u | fmt -2500`
        BADWORDS="$STILLBAD"
    fi
fi

# If there are still bad words left
# then issue a warning and exit with an error code.
# Allow long line(s) to allow pasting into SPELLEX header line easily.
if [ "" != "$BADWORDS" ]; then
    echo "$BADWORDS" | awk '{print "WARNING: spell-TODO: "$0}'
    exit 1
fi

exit 0

# % sh script/spellb.sh < .note-on-site-technicals-61.html
# INFO: spell: Azizsoft GSC M1 Qwiic SVG Throbber WPT Wikimedia cluestick
# INFO: spell: conexDHW hunspell isAccessibleForFree isn spellb symlink
# INFO: spell: throbber throbbers ve
