#!/usr/bin/perl -w
# (C) 2003-2007 Willem Jan Hengeveld <itsme@xs4all.nl>
# Web: http://www.xs4all.nl/~itsme/
#      http://wiki.xda-developers.com/
#
# $Id$
#

use strict;
# script to list differences between 2 dirsummary xml output files.

use Getopt::Long;

use XML::Simple;

use Dumpvalue;
my $d= new Dumpvalue;
$|=1;
$/=undef;

# XMLin wants filename to start with a path - append current dir if no path present.
(my $file1= shift) =~ s{^(?!./|/|\\)}{./};
(my $file2= shift) =~ s{^(?!./|/|\\)}{./};

my $sum1= XMLin($file1);
my $sum2= XMLin($file2);

my @g_differences;
my @g_missingfrom1st;
my @g_missingfrom2nd;

if (!differences($sum1->{item}{item}, $sum2->{item}{item})) {
    for my $f (@g_differences) {
        print "different: $f\n";
    }
    for my $f (@g_missingfrom1st) {
        print "missing from $file1 $f\n";
    }
    for my $f (@g_missingfrom2nd) {
        print "missing from $file2 $f\n";
    }
}

exit(0);

sub differences {
    my ($sum1, $sum2, $path) = @_;
    $path ||="";

    if (ref $sum1 ne "HASH" || ref $sum2 ne "HASH" || !exists $sum1->{md5} || !defined $sum1->{md5} || !exists $sum2->{md5} || !defined $sum2->{md5}) {
        warn "$path: something wrong\n"; 
        return 2;
    }
    if ($sum1->{md5} eq $sum2->{md5}) {
        return 1;
    }
    for my $itemname (keys %{$sum1->{item}}) {
        if (exists $sum2->{item}{$itemname}) {
            my $rc= differences($sum1->{item}{$itemname}, $sum2->{item}{$itemname}, "$path/$itemname");
            if ($rc==0) {
                push @g_differences, "$path/$itemname";
            }
            elsif ($rc==2) {
            }
        }
        else {
            push @g_missingfrom2nd, "$path/$itemname";
        }

    }
    for my $itemname (keys %{$sum2->{item}}) {
        if (!exists $sum1->{item}{$itemname}) {
            push @g_missingfrom1st, "$path/$itemname";
        }
    }

    return 0;
}
