#!/bin/sh
# docs/manual/*.md and docs/reference/*.md as C, for src/manual.inc: the
# topics `pic help` and the terminal's /help show, compiled in so the binary
# needs no file. Each topic is its file's text in chunks of at most 3500
# bytes, split at line ends (C11 promises string literals of 4095 bytes), and
# its title is the file's first "# " line. start comes first, then the other
# manual topics, then the reference.
set -eu
cd "$(dirname -- "$0")/.."
files=$(
    printf '%s\n' docs/manual/start.md
    ls docs/manual/*.md | LC_ALL=C sort | grep -vx docs/manual/start.md
    ls docs/reference/*.md | LC_ALL=C sort
)
dups=$(for f in $files; do basename "$f" .md; done | LC_ALL=C sort | uniq -d)
[ -z "$dups" ] || { printf 'manual-inc: two topics named %s\n' "$dups" >&2; exit 1; }
printf '/* Generated from docs/manual and docs/reference by tools/manual-inc.sh; do not edit. */\n'
for f in $files; do
    head -1 "$f" | grep -q '^# ' || { printf 'manual-inc: %s does not start with a "# " title\n' "$f" >&2; exit 1; }
    awk -v id="$(basename "$f" .md | tr -- '-.' '__')" '
    BEGIN { printf "static const char *const help_%s[] = {\n", id; size = 0 }
    {
        line = $0
        if (size > 0 && size + length(line) + 1 > 3500) { printf ",\n"; size = 0 }
        size += length(line) + 1
        gsub(/\\/, "\\\\", line); gsub(/"/, "\\\"", line); gsub(/\?\?/, "?\\?", line)
        printf "%s\"%s\\n\"", (size == length($0) + 1 ? "" : "\n"), line
    }
    END { printf ",\nNULL};\n" }' "$f"
done
printf 'static const pic_help_topic help_topics[] = {\n'
for f in $files; do
    name=$(basename "$f" .md)
    title=$(head -1 "$f" | sed 's/^# //; s/\\/\\\\/g; s/"/\\"/g')
    case "$f" in docs/reference/*) ref=1 ;; *) ref=0 ;; esac
    printf '    {"%s", "%s", %s, help_%s},\n' "$name" "$title" "$ref" "$(printf %s "$name" | tr -- '-.' '__')"
done
printf '};\n'
