#!/usr/bin/perl -w

# Script to check the FAQ source and make sure I have all the numbers
# in the right order without duplication. Also check the numbers of blank
# lines. It gives up on any error (other than bad blank line counts).

sub oops {
print "\nLine $line: $_[0]\n";
print;
exit 1;
}

sub poops {
print "\nLine $line: $_[0]\n";
print;
$precede_fail = 1;
}


$line = 0;
$section = -1;
$expect_answer = 0;
$precede_fail = 0;

while (<>)
  {
  $line++;
  if (/^\s*$/)
    {
    $blankcount++;
    next;
    }
  $preceded = $blankcount;
  $blankcount = 0;

  if (/^(\d+)\./)
    {
    &poops("$preceded empty lines precede (3 expected)") if $preceded != 3;
    &oops(sprint("Answer %02d%02d is missing\n", $section, $question))
      if $expect_answer;
    $section = $1;
    $question = ($section == 20)? 0 : 1;
    $expected = 1;
    if ($section == 99)
      {
      $c = 1;
      $f = 1;
      }
    next;
    }

  if ($section != 99)
    {
    if (/^Q(\d\d)(\d\d):/)
      {
      &poops("$preceded empty lines precede ($expected expected)")
        if $preceded != $expected;
      $expected = 2;

      &oops("Answer expected") if $expect_answer;
      &oops("Q$1$2 is in the wrong section") if ($1 != $section);
      &oops("Q$1$2 is out of order") if $2 != $question;

      $expect_answer = 1;
      next;
      }

    if (/^A(\d\d)(\d\d):/)
      {
      &poops("$preceded empty lines precede (1 expected)") if $preceded != 1;

      &oops("Question expected") if !$expect_answer;
      &oops("A$1$2 is in the wrong section") if $1 != $section;
      &oops("A$1$2 is out of order") if $2 != $question++;

      $expect_answer = 0;
      next;
      }
    }

  else
    {
    if (/^C(\d\d\d):/)
      {
      &oops("C$1 is mixed up in the Fs") if $f != 1;
      # Some Cxxx configs are omitted (not translated from Exim 3) so can
      # only check increasing number.
      &oops("C$1 is out of order") if $1 < $c;
      $c = $1;
      }
    elsif (/^F(\d\d\d):/)
      {
      &oops("F$1 is out of order") if $1 != $f++;
      next;
      }
    }
  }

exit 1 if $precede_fail;

# End