#!/bin/sh
# conform-doc-readme [-hnq] file ... -- the README of a port in the form of the OpenBSD template
# (infrastructure/templates/README.template). One stderr line per fault, "<file>:<line>: <what>";
# stdout: the count. rc 0 clean, 1 faults, 2 usage or no file. -n is accepted for the convention of
# the family and changes nothing. Checked: ASCII only; 80 columns at most; no trailing blank on a
# line; no blank last line; the frame (a rule of 80 characters, "| Running <name> on OpenBSD", the
# same rule); a "=" or "-" underline as long as the title above it.
PATH=/bin:/sbin:/usr/bin:/usr/sbin
set -u
export LC_ALL=C

usage() { echo "usage: conform-doc-readme [-hnq] file ..." >&2; }
quiet=0
while getopts hnq o; do
	case $o in
	h) usage; exit 0 ;;
	n) ;;
	q) quiet=1 ;;
	*) usage; exit 2 ;;
	esac
done
shift $((OPTIND - 1))
[ $# -ge 1 ] || { usage; exit 2; }

faults=0
for f in "$@"; do
	[ -f "$f" ] || { echo "conform-doc-readme: $f: no such file" >&2; exit 2; }
	out=$(awk '
		function fault(m) { printf "%s:%d: %s\n", FILENAME, FNR, m; n++ }
		{ line[FNR] = $0 }
		/[^ -~]/ { fault("byte outside ASCII") }
		length($0) > 80 { fault("longer than 80 columns") }
		/[ \t]$/ { fault("trailing blank") }
		FNR > 1 && $0 ~ /^(=+|-+)$/ && length($0) >= 3 && prev !~ /^[ \t]*$/ && prev !~ /^\+/ && length($0) != length(prev) { fault("underline is not as long as the title above it") }
		{ prev = $0 }
		END {
			if (FNR == 0) { fault("empty file") }
			else {
				if (line[FNR] ~ /^[ \t]*$/) { FNR_save = FNR; fault("blank last line") }
				if (line[1] !~ /^\+-+$/ || length(line[1]) != 80) { FNR = 1; fault("line 1 is not a rule of 80 characters: +---") }
				if (line[2] !~ /^\| Running .+ on OpenBSD$/) { FNR = 2; fault("line 2 is not: | Running <name> on OpenBSD") }
				if (line[3] != line[1]) { FNR = 3; fault("line 3 is not the same rule as line 1") }
			}
			exit n > 0 ? 1 : 0 }' "$f" 2>&1)
	if [ -n "$out" ]; then
		echo "$out" >&2
		faults=$((faults + $(echo "$out" | wc -l)))
	fi
done

[ "$quiet" -eq 1 ] || echo "conform-doc-readme: $faults faults"
[ "$faults" -eq 0 ]
