#!/usr/bin/env bash
#
# html-signatures.sh - populate quick HTML build records
#
# Copyright (c) 2026 by Landon Curt Noll.  All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby granted,
# provided that the above copyright, this permission notice and text
# this comment, and the disclaimer below appear in all of the following:
#
#       supporting documentation
#       source copies
#       source works derived from this source
#       binaries derived from this source or from derived source
#
# LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
# EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
# USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
#
# chongo (Landon Curt Noll, http://www.isthe.com/chongo/index.html) /\oo/\
#
# Share and enjoy! :-)
#
# TOOL_OPTION and QUICK_HTML_BUILD_YEAR are consumed by the sourced helper.
# shellcheck disable=SC2034
VERSION="1.2.0 2026-12-04"

set -o pipefail
shopt -s nullglob

NAME=$(basename "$0")
USAGE="usage: $0 [-h] [-V] all|missing|check

	-h		print help message and exit
	-V		print version string and exit

	all		recreate records for existing generated HTML files
	missing		create only missing records
	check		report missing or stale records without changing files

The all and missing modes remove records whose HTML files are missing. They
trust existing HTML and do not generate or modify it; use make www to rebuild
the site.

Exit codes:
     0         all OK, or version string printed
     1         site data or internal error
     2         help printed or command line error

$NAME version: $VERSION"

case "${1-}" in
    -h|--help) echo "$USAGE" >&2; exit 2 ;;
    -V|--version) echo "$VERSION"; exit 0 ;;
    all|missing|check) MODE="$1" ;;
    *) echo "$USAGE" >&2; exit 2 ;;
esac
[[ $# == 1 ]] || { echo "$USAGE" >&2; exit 2; }

TOPDIR=$(git rev-parse --show-toplevel) || exit 1
cd "$TOPDIR" || exit 1
# shellcheck source=bin/quick-deps.sh disable=SC1091
. bin/quick-deps.sh || exit 1

SITE_URL="https://www.ioccc.org"
QUICK_HTML_BUILD_YEAR=$(date '+%Y') || exit 1
RESULT=0
declare -a BAD_SIG=() MISSING_SIG=()
declare -A SEEN=()
LOCATION_TOOL=$(type -P location)
[[ -n $LOCATION_TOOL ]] || LOCATION_TOOL="bin/location"
JVAL_WRAPPER=$(type -P jval-wrapper.sh)
[[ -n $JVAL_WRAPPER ]] || JVAL_WRAPPER="bin/jval-wrapper.sh"
YEARS_INPUTS=(bin/gen-years.sh "$JVAL_WRAPPER")
YEARS_INVALID=""
if [[ ! -r bin/gen-top-html.sh || ! -r bin/md2html.cfg || ! -r .top || ! -s .top ]]; then
    echo "$0: ERROR: missing page list, Markdown configuration, or .top" >&2
    exit 1
fi
LIST_FILE=$(mktemp "${TMPDIR:-/tmp}/html-signatures.XXXXXX") || {
    echo "$0: ERROR: cannot create temporary file" >&2
    exit 1
}
trap 'quick_html_abort; rm -f -- "$LIST_FILE"' EXIT
trap 'exit 1' HUP INT TERM

# These arguments match the top-level Makefile's default quick generators.
# The record asserts that existing HTML is current; it does not regenerate it.
record_page()
{
    local output="$1" match="$2" kind="$3"
    local record=".quick-html-cache/$output.sig"
    local page_year entry_dir handles handle
    local -a inputs=()
    if [[ $MODE == check ]]; then
        SEEN["$output"]=1
        if [[ ! -e $record && ! -L $record ]]; then
            MISSING_SIG+=("$output")
            return 0
        fi
        if [[ ! -f $output || -L $output || ! -f $record || -L $record ]]; then
            BAD_SIG+=("$output")
            return 0
        fi
    else
        if [[ ! -e $output && ! -L $output ]]; then
            if [[ -e $record.pending || -L $record.pending ]]; then
                echo "$0: ERROR: build marker exists for $output: $record.pending" >&2
                RESULT=1
            fi
            return 0
        fi
        # Lock first, then recheck the output and record: generators use the
        # same marker, so neither can change them while we sign the page.
        if ! quick_html_lock "$output"; then
            RESULT=1
            return 0
        fi
        if [[ ! -e $output && ! -L $output ]]; then
            quick_html_unlock || RESULT=1
            return 0
        fi
        if [[ ! -f $output || -L $output ]]; then
            echo "$0: ERROR: not a regular non-symlink HTML file: $output" >&2
            RESULT=1
            quick_html_unlock || RESULT=1
            return 0
        fi
        if [[ $MODE == missing && -e $record ]]; then
            quick_html_unlock || RESULT=1
            return 0
        fi
    fi
    case "$kind" in
        top)
            QUICK_HTML_GENERATOR="bin/gen-top-html.sh"
            DOCROOT_SLASH="./"; TAGLINE="$QUICK_HTML_GENERATOR"
            TOOL_OPTION=(-v 1 -t "$TAGLINE" -D "$DOCROOT_SLASH")
            ;;
        authors|location|years)
            QUICK_HTML_GENERATOR="bin/gen-$kind.sh"
            DOCROOT_SLASH="./"; TAGLINE="$QUICK_HTML_GENERATOR"
            TOOL_OPTION=(-v 1 -t "$TAGLINE" -U "$SITE_URL/$output" -D "$DOCROOT_SLASH")
            ;;
        year)
            QUICK_HTML_GENERATOR="bin/gen-year-index.sh"
            DOCROOT_SLASH="../../"; TAGLINE="$QUICK_HTML_GENERATOR"
            TOOL_OPTION=(-t "$TAGLINE")
            ;;
        entry)
            QUICK_HTML_GENERATOR="bin/quick-readme2index.sh"
            DOCROOT_SLASH="../../"; TAGLINE="bin/readme2index.sh"
            TOOL_OPTION=(-v 1 -t "$TAGLINE" -U "$SITE_URL/$output")
            ;;
        other)
            QUICK_HTML_GENERATOR="bin/gen-other-html.sh"
            DOCROOT_SLASH="../../"; TAGLINE="$QUICK_HTML_GENERATOR"
            TOOL_OPTION=(-t "$TAGLINE" -v 1 -w "$SITE_URL")
            ;;
        *) echo "$0: ERROR: unknown page kind: $kind" >&2; return 1 ;;
    esac
    if [[ $MODE == check ]]; then
        # Match the default quick generators' per-page prerequisites as well as
        # their fingerprint options. Keep these lists in sync with those tools.
        case "$kind" in
            top)
                inputs=("$match" bin/gen-top-html.sh)
                [[ $match == status.md ]] && inputs+=(status.json bin/status2html.sh)
                ;;
            authors)
                inputs=(author/*.json [12][0-9][0-9][0-9]/*/.entry.json
                        bin/gen-authors.sh "$JVAL_WRAPPER" bin/combine_author_handle.sh "$LOCATION_TOOL")
                ;;
            location)
                inputs=(author/*.json bin/gen-location.sh "$JVAL_WRAPPER" "$LOCATION_TOOL")
                ;;
            years)
                inputs=("${YEARS_INPUTS[@]}")
                if [[ -n $YEARS_INVALID ]]; then
                    BAD_SIG+=("$output")
                    return 0
                fi
                ;;
            year)
                page_year="${output%%/*}"
                inputs=("$match" bin/gen-year-index.sh)
                if [[ $output == "$page_year/index.html" ]]; then
                    inputs+=("$page_year/.year" "$page_year"/*/.entry.json "$page_year"/*/.path
                             bin/subst.year-index.sh bin/subst.year-navbar.awk
                             bin/output-year-index.sh bin/jval-wrapper.sh)
                elif [[ $output == "$page_year/challenge.html" ]]; then
                    inputs+=(bin/subst.year-challenge.sh)
                fi
                ;;
            entry)
                entry_dir="${output%/index.html}"
                page_year="${entry_dir%%/*}"
                if ! handles=$(bin/jval-wrapper.sh -b -q -P -- "$entry_dir/.entry.json" './/author_handle') ||
                   [[ -z $handles ]]; then
                    echo "$0: ERROR: unable to obtain author handles from: $entry_dir/.entry.json" >&2
                    BAD_SIG+=("$output")
                    return 0
                fi
                inputs=("$entry_dir/.entry.json" "$match" "$entry_dir/.path" "$page_year/.year")
                for handle in $handles; do inputs+=("author/$handle.json"); done
                inputs+=("$LOCATION_TOOL" bin/quick-readme2index.sh bin/subst.entry-index.sh
                         bin/subst.entry-navbar.awk bin/output-index-author.sh
                         bin/output-index-inventory.sh bin/manifest.entry.json.awk bin/jval-wrapper.sh)
                ;;
            other)
                inputs=("$match" bin/gen-other-html.sh bin/othermd2html.sh)
                ;;
            *) echo "$0: ERROR: unknown page kind: $kind" >&2; return 1 ;;
        esac
        if ! quick_html_current "$output" "$match" "${inputs[@]}"; then
            BAD_SIG+=("$output")
        fi
    elif ! quick_html_record "$output" "$match"; then
        echo "$0: ERROR: cannot record $output" >&2
        RESULT=1
        quick_html_abort || RESULT=1
    fi
}

# Read the generator's own list rather than maintaining another page list.
TOP_COUNT=0
while IFS= read -r line; do
    if [[ $line =~ ^TOP_MD_SET\+=\(\"([^\"]+)\"\)$ ]]; then
        (( TOP_COUNT += 1 ))
        name="${BASH_REMATCH[1]}"
        if [[ $name == /* || /$name/ == *'/../'* || /$name/ == *'/./'* || $name == *//* ]]; then
            echo "$0: ERROR: unsafe top-level page name: $name" >&2
            RESULT=1
            continue
        fi
        case "$name" in
            bin/README|inc/README|next/README|author/README|archive/historic/README)
                output="${name%/README}/index.html" ;;
            *) output="$name.html" ;;
        esac
        record_page "$output" "$name.md" top
    fi
done < bin/gen-top-html.sh
if (( TOP_COUNT == 0 )); then
    echo "$0: ERROR: no top-level pages found in bin/gen-top-html.sh" >&2
    exit 1
fi

for name in authors location; do
    record_page "$name.html" "$name.md" "$name"
done

# A Markdown file is eligible only if it selects a non-fallback cfg rule.
configured_markdown()
{
    local match="$1" line
    while IFS= read -r line || [[ -n $line ]]; do
        [[ -z $line || $line == [[:space:]]* || $line == \#* ]] && continue
        # shellcheck disable=SC2053 # Configuration patterns are Bash globs.
        if [[ $match == $line ]]; then
            [[ $line != '*.md' && $line != '*' ]]
            return
        fi
    done < bin/md2html.cfg
    return 1
}

while IFS= read -r year; do
    [[ -n $year ]] || continue
    if [[ ! $year =~ ^[12][0-9][0-9][0-9]$ || -L $year ]]; then
        echo "$0: ERROR: unsafe year directory: $year" >&2
        RESULT=1
        YEARS_INVALID="true"
        continue
    fi
    YEARS_INPUTS+=("$year/.year")
    [[ -e $year/$year.tar.bz2 ]] || YEARS_INVALID="true"
    for name in README rules guidelines challenge; do
        source="$year/$name.md"
        if [[ $MODE == check && $name == README ]]; then
            : # The year index is required even if its source is missing.
        elif [[ $MODE == check ]]; then
            [[ -s $source ]] || continue
        else
            [[ -f $source ]] || continue
        fi
        if [[ $name == README ]]; then output="$year/index.html"; else output="$year/$name.html"; fi
        configured_markdown "$source" && record_page "$output" "$source" year
    done
    if [[ ! -r $year/.year ]]; then
        echo "$0: ERROR: cannot read $year/.year" >&2
        RESULT=1
        YEARS_INVALID="true"
        continue
    fi
    while IFS= read -r entry; do
        [[ -n $entry ]] || continue
        entry_name="${entry#"$year"/}"
        if [[ $entry_name == "$entry" || -z $entry_name || $entry_name == */* ||
              $entry_name == . || $entry_name == .. || -L $entry ]]; then
            echo "$0: ERROR: unsafe entry directory: $entry" >&2
            RESULT=1
            YEARS_INVALID="true"
            continue
        fi
        YEARS_INPUTS+=("$entry/.entry.json")
        [[ -s $entry/README.md ]] || YEARS_INVALID="true"
        record_page "$entry/index.html" "$entry/README.md" entry
        if [[ ! -d $entry ]]; then
            echo "$0: ERROR: missing entry directory: $entry" >&2
            RESULT=1
            continue
        fi
        if ! find "$entry" -type f -name '*.md' ! -name README.md ! -name remarks.md -print0 > "$LIST_FILE"; then
            echo "$0: ERROR: cannot enumerate markdown in $entry" >&2
            RESULT=1
            continue
        fi
        while IFS= read -r -d '' source; do
            configured_markdown "$source" && record_page "${source%.md}.html" "$source" other
        done < "$LIST_FILE"
    done < "$year/.year"
done < .top
record_page years.html years.md years

# Only orphaned records are removed; existing records are left alone in
# missing-only mode, even if they are stale.
if [[ -d .quick-html-cache ]]; then
    if ! find .quick-html-cache \( -type f -o -type l \) -name '*.sig' -print0 > "$LIST_FILE"; then
        echo "$0: ERROR: cannot enumerate cached records" >&2
        exit 1
    fi
    while IFS= read -r -d '' record; do
        output="${record#.quick-html-cache/}"
        output="${output%.sig}"
        if [[ $MODE == check ]]; then
            # Unknown or orphaned records cannot be validated against a
            # current generated page, even if an unrelated HTML file exists.
            if [[ ! ${SEEN[$output]+present} ]]; then
                BAD_SIG+=("$output")
            fi
        elif [[ ! -f $output ]]; then
            # The output may appear during a rebuild; check again under the
            # same lock used by generators before removing an orphan record.
            if ! quick_html_lock "$output"; then
                RESULT=1
                continue
            fi
            if [[ ! -f $output ]] &&
               ! python3 bin/html_cache.py remove "$output" "${QUICK_HTML_CACHE_ID-}"; then
                echo "$0: ERROR: cannot remove orphaned record: $record" >&2
                RESULT=1
            fi
            quick_html_unlock || RESULT=1
        fi
    done < "$LIST_FILE"
fi
if [[ $MODE == check ]]; then
    echo '=-=-= HTML files that do not match their .sig file starts below =-=-='
    if (( ${#BAD_SIG[@]} )); then printf '%s\n' "${BAD_SIG[@]}"; RESULT=1; fi
    echo '=-=-= HTML files that do not match their .sig file ends above =-=-='
    echo '=-=-= HTML files with missing .sig files starts below =-=-='
    if (( ${#MISSING_SIG[@]} )); then printf '%s\n' "${MISSING_SIG[@]}"; RESULT=1; fi
    echo '=-=-= HTML files with missing .sig files ends above =-=-='
    (( RESULT )) || echo '=-=-= No .sig errors found =-=-='
fi
exit "$RESULT"
