#!/usr/bin/perl -W

# compare two config.txt files and show the difference
# could use diff and a perl oneliner, but then we also need to think :-)

if (@ARGV != 2) {
    print "usage:\n";
    print "\t diff_conf file1.txt file2.txt\n\n";
    exit;
}

$errors=0;

open(CONFIG, "<$ARGV[0]") or die "can't open $ARGV[0]";

$line_number=0;
while($l = <CONFIG>) {
    chomp $l;
    $line_number++;

    if ($l =~ /^\s*($|\/\/|\#|;)/) {  # skip lines consisting of comments only (empty line, //, #, ;)
	next;
    }

    if ($l =~ /(\w+(\[\w+\])?)=([a-fA-F0-9]{1,2})\b/) {  # match a name=FF or name[1]=FF
	$varname = $1;
	$varvalue = $3;
	
	$conf1{$varname}=$varvalue;
    } else {
	print STDERR "ERROR @ line $line_number in [$ARGV[0]]: can't understand \"$l\"\n";
	$errors += 1;
    }
}

open(CONFIG, "<$ARGV[1]") or die "can't open $ARGV[1]";

$line_number=0;
while($l = <CONFIG>) {
    chomp $l;
    $line_number++;

    if ($l =~ /^\s*($|\/\/|\#|;)/) {  # skip lines consisting of comments only (empty line, //, #, ;)
	next;
    }

    if ($l =~ /(\w+(\[\w+\])?)=([a-fA-F0-9]{1,2})\b/) {  # match a name=FF or name[1]=FF
	$varname = $1;
	$varvalue = $3;
	
	$conf2{$varname}=$varvalue;
    } else {
	print STDERR "ERROR @ line $line_number in [$ARGV[1]]: can't understand \"$l\"\n";
	$errors += 1;
    }
}

close CONFIG;

print "Diff: file1 <> file2\n";
foreach $n (sort keys %conf1) {
    if (defined($conf2{$n})) {
	$a = $conf1{$n};
	$a =~ tr/[a-f]/[A-F]/;

	$b = $conf2{$n};
	$b =~ tr/[a-f]/[A-F]/;

	if ($a ne $b) {
	    print "$n=$conf1{$n} <> $n=$conf2{$n}\n";
	}
	delete $conf1{$n};
	delete $conf2{$n};
    }
} 
 
if (keys %conf1) {
    print "\nFound in file1 but not in file2:\n";
    foreach $n (sort keys %conf1) {
	print "$n=$conf1{$n}\n";
	delete $conf1{$n};
    } 
}

if (keys %conf2) {
    print "\nFound in file2 but not in file1:\n";
    foreach $n (sort keys %conf2) {
	print "$n=$conf2{$n}\n";
	delete $conf2{$n};
    }
}
