use strict;
my (%old, %new);
my ($key, $value, $section, $subsecprinted, $sectionprinted);

if((scalar @ARGV) != 2) {
    die "Usage: perl mbdiff <first file> <second file>\n";
}

open(FILE, $ARGV[0]) or die "Failure to open $ARGV[0]:$!";
$section = "[/]";
while(<FILE>){
    chomp;
    if(m/^\[(.*)\]$/) {
        $section = $_;
        next;
    }

    ($key, $value) = split / :/;

    $old{$section}{$key} = $value;
    
}
close(FILE);

open(FILE, $ARGV[1]) or die "Failure to open $ARGV[0]:$!";
$section = "[/]";
while(<FILE>){
    chomp;
    if(m/^\[(.*)\]$/) {
        $section = $_;
        next;
    }

    ($key, $value) = split / :/;

    $new{$section}{$key} = $value;
    
}
close(FILE);

print "Metabase:\n";
#
# added stuff
#

#
# added entries
#
$sectionprinted = 0;
foreach $section (sort keys %new) {
    $subsecprinted = 0;
    foreach $key (sort keys %{$new{$section}}) {
        if(!defined($old{$section}{$key})) {
            if(!$sectionprinted) {
                $sectionprinted = 1;
                print("      Added:\n");
            }
            if(!$subsecprinted) {
                print("        $section\n");
                $subsecprinted = 1;
            }
            print("            $key : ", $new{$section}{$key}, "\n");
        }
    }
}

#
# deleted entries
#
$sectionprinted = 0;
foreach $section (sort keys %old) {
    $subsecprinted = 0;
    foreach $key (sort keys %{$old{$section}}) {
        if(!defined($new{$section}{$key})) {
            if(!$sectionprinted) {
                $sectionprinted = 1;
                print("      Deleted:\n");
            }
            if(!$subsecprinted) {
                print("        $section\n");
                $subsecprinted = 1;
            }
            print("            $key\n");
        }
    }
}

#
# changed entries
#
$sectionprinted = 0;
foreach $section (sort keys %old) {
    $subsecprinted = 0;
    foreach $key (sort keys %{$old{$section}}) {
    
        if(defined($new{$section}{$key})) {
            if($new{$section}{$key} eq $old{$section}{$key}) {
                next;
            }
            
            if(!$sectionprinted) {
                $sectionprinted = 1;
                print("      Changed:\n");
            }
            if(!$subsecprinted) {
                print("        $section\n");
                $subsecprinted = 1;
            }
            print("            $key : ", $old{$section}{$key}, "\n");
            print("          to\n");
            print("            $key : ", $new{$section}{$key}, "\n");
        }
    }
}