#!/bin/bash
#
# usage: maint/update-tocs [--check]
#
# Updates the embedded Table of Contents in the following files:
process_files () {
    process_file doc/reference.md
    process_file macros/HACKING.md
}
# We do it like this because we don't want to have this done by
# a build.rs, which would have to run on every build.
#
# The CI will check that the TOC is up to date, but this is only
# treated as a warning.

set -e -o pipefail

case "$*" in
    --check) install=false;;
    '') install=true;;
    *) echo >&2 'bad usage'; exit 1;;
esac

problems=false

process_file () {
    file=$1
    perl <$file -wne '
	next unless s{^\#(\#+)\s+}{};
	my $depth = length($1);
	next if $depth > 2;
	print "   " x $depth, "* ";
	chomp;
	my $txt = $_;
	s{--+}{}g;
	s{[^- \w]}{}g;
	y/ A-Z/-a-z/;
	print "[$txt](#$_)\n";
    ' | perl -wne '
	BEGIN {
	    $toc = do { local $/ = undef; <STDIN>; };
	    $toc =~ s{\n+$}{}s;
	}
	print unless $skip;
	if (m{^\Q<!--##toc##-->}) {
            $skip = 1;
	    print $toc, "\n\n";
	    next;
    	}
	if (!m{^ +\*}) {
            $skip = 0;
	}
    ' $file >$file.new

    if $install; then
	mv -f $file.new $file
    else
	set +e
	diff -u $file $file.new
	rc=$?
	set -e
	case $rc in
	    0) ;;
	    1) problems=true ;;
	    *) exit $rc ;;
	esac
    fi
}

process_files

if $problems; then
    echo 'Documentation TOC mismatch - rerun maint/update-tocs'
    exit 1
fi
