#!/usr/bin/perl

####################
#    Copyright (C) 2014 by Raphael Geissert <geissert@debian.org>
#
#    This file is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This file is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this file  If not, see <http://www.gnu.org/licenses/>.
#
#    On Debian systems, the complete text of the GNU General
#    Public License 3 can be found in '/usr/share/common-licenses/GPL-3'.
####################

use warnings;
use strict;

# recursive function
sub parse_submenu;

sub should_skip;
sub is_submenu;
sub is_function;
sub get_shortcut;

our $found_error = 0;

# there's a main, implicit, menu so start over there:
parse_submenu('main');

exit($found_error);

sub parse_submenu {
    my $this_submenu = shift;
    my %shortcuts;

    while (<>) {
	chomp;
	s/^\s+//;
	next if should_skip($_);

	if (is_submenu($_) || is_function($_)) {
	    my $text = get_text($_);
	    my $short = get_shortcut($text);

	    if ($short && exists($shortcuts{$short})) {
		print STDERR "error: shortcut '$short' of '$this_submenu' menu already in use\n";
		print STDERR "\tfirst declared on line $shortcuts{$short}, collision on line $.\n";
		$found_error = 1;
	    } elsif ($short) {
		$shortcuts{$short} = $.;
	    }

	    if (is_submenu($_)) {
		parse_submenu($text);
	    }
	} elsif ($_ eq 'end') {
	    return;
	} elsif ($_ eq 'hline') {
	    next;
	} else {
	    die ('error: unknown item found');
	}
    }
}

sub should_skip {
    my $l = shift;
    return (length($l) == 0 || $l =~ m/^#/);
}

sub is_submenu {
    my $l = shift;
    return ($l =~ m/^submenu/);
}

sub is_function {
    my $l = shift;
    return ($l =~ m/^function/);
}

sub get_text {
    my $l = shift;
    $l =~ m/"(.*?)"/;
    return ($1 || '');
}

sub get_shortcut {
    my $l = shift;
    $l =~ m/&(.)/;
    return uc($1 || '');
}
