#!/usr/bin/perl
#
# Search for missing 'itemhelp' entries in menus

use strict;
use warnings;

sub trim($) {
  my ($str) = @_;
  $str =~ s/^[\s]+//go;
  $str =~ s/[\s]+$//go;
  return $str;
}

my $lastitem      = undef;
my $lastitem_loc  = undef;
my $lastitem_name = undef;

foreach my $line (<>) {
  chomp($line);
  if ($line =~ /^([^:]+:[0-9]+):/o) {
    my ($loc,$rest) = ($1,$');
    eval {
      if ($rest =~ /[ ]*(item|itemhelp):/io) {
        my ($tag,$content) = (lc($1), trim($'));
        if ($tag eq 'item') {
          if (defined $lastitem) {
            print STDERR "$lastitem_loc: Warning: item '$lastitem_name' lacks an 'itemhelp' entry!\n";
          }
          $lastitem      = $line;
          $lastitem_loc  = $loc;
          $lastitem_name = $content;
        }
        elsif ($tag eq 'itemhelp') {
          if (not defined $lastitem) {
            die "detected 'itemhelp' w/o preceeding 'item'\n ";
          }
          $lastitem = undef;
          if ($content eq '') {
            die "itemhelp lacks name of helpfile\n ";
          }
        }
        else { die "Unexpected tag '$tag'\n "; }
      }
      else {
        die "expected 'item' or 'itemhelp' (grep failure?)\n ";
      }
    };
    if ($@) {
      die "$loc: Error: $@";
    }
  }
  else {
    die "Error: Unexpected line: '$line'\n ";
  }
}
