#!/usr/bin/perl

use strict;
use warnings;
use Getopt::Long;
use DistroDBTools;

my (%old,%cur,%new,%newold,%manual);

my $oldfile='binary/10-distrodb-old.txt';
my $curfile='binary/40-distrodb.txt';
my $newfile='binary/40-distrodb-new.txt';

&DistroDBTools::read_map(\%old, $oldfile) if -f $oldfile;
&DistroDBTools::read_map(\%cur, $curfile) if -f $curfile;
&DistroDBTools::read_map(\%new, $newfile);
map {&DistroDBTools::read_map(\%manual, $_)}
    grep {$_ ne $oldfile and $_ ne $curfile and $_ ne $newfile}
    glob 'binary/*.txt';

foreach my $key (keys(%old)) {
    next if $new{$key};
    my @val=@{$old{$key}};
    next if @val>1 or $val[0] eq $key;
    $newold{$key}=\@val;
}
foreach my $key (keys(%cur)) {
    next if $new{$key} or $manual{$key};
    my @val=@{$cur{$key}};
    next if @val>1 or $val[0] eq $key;
    $newold{$key}=\@val;
}

unlink $oldfile;
&DistroDBTools::write_map(\%newold, $oldfile) if %newold or -f $oldfile;
system('mv', $newfile, $curfile);
