package PkgCache;

use v5.20;
use Path::Tiny;

use Config::Model::Dpkg::Dependency;

my $cache_file = path('t/dependency-cache.txt')->absolute;

$Config::Model::Dpkg::Dependency::use_test_cache = 1;
untie %Config::Model::Dpkg::Dependency::cache;
%Config::Model::Dpkg::Dependency::cache = ();

say "Loading cache";

foreach my $line ($cache_file->lines) {
    chomp $line;
    next unless $line;
    my ($k,$v) = split m/ => /, $line ;
    $Config::Model::Dpkg::Dependency::cache{$k} = time . ' '. $v ;
}

END {
    return if $::DebianDependencyCacheWritten ;
    my %h = %Config::Model::Dpkg::Dependency::cache ;
    do { s/^\d+ //;} for values %h ; # remove time stamp
    my $str = join ("\n", map { "$_ => $h{$_}" ;} sort keys %h) ;

    if ( -w $cache_file ) {
        say "writing back cache file";
        # not a big deal if cache cannot be written back
        $cache_file->spew($str);
        $::DebianDependencyCacheWritten=1;
    }
    else {
        say "can't write cache file";
    }
}

1;
