#!/usr/bin/perl

use strict;
use warnings;

use lib 'lib';
use lib 'tools';

use LWP::UserAgent;

use Changelog;
use GLPI::Agent::Tools;

# Set maximum time to get an answer and time to wait between each try
my $maxdelay = time + 300;
my $trydelay = 15;

# Touch usb.ids file with stored date to make mirror API works as expected
my ($date, $time) = getFirstMatch(
    file    => "share/usb.ids",
    pattern => qr/^#\s+Date:\s+([0-9-]+)\s+([0-9:]+)/,
);
system("touch -d '$date $time' share/usb.ids") if $date && $time;

my $ua = LWP::UserAgent->new();

my $response;
while (time<=$maxdelay && !($response && $response->is_success())) {

    if ($response) {
        print "Retrying in ${trydelay}s after: ".$response->status_line()."\n";
        sleep $trydelay;
    }

    $response = $ua->mirror(
        "http://www.linux-usb.org/usb.ids",
        "share/usb.ids"
    );

    if ($response->status_line =~ /Not Modified/) {
        print "share/usb.ids is still up-to-date\n";
        exit(0);
    }
}

die "Update failed: ".$response->status_line()."\n"
    unless $response->is_success();

my $version = getFirstMatch(
    file    => "share/usb.ids",
    pattern => qr/^#\s+Version:\s+([0-9.]+)/,
);

my $previous = getFirstMatch(
    file    => "Changes",
    pattern => qr/Updated usb.ids to ([0-9.]+) version/,
);

if ($version eq $previous) {
    print "share/usb.ids was still up-to-date\n";
    exit(0);
}

my $Changes = Changelog->new( file => "Changes" );
$Changes->add( inventory => "Updated usb.ids to $version version" );
$Changes->write();
