#!/usr/bin/perl

use strict;
use warnings;
use LWP::UserAgent;
use Sys::Hostname;
use Data::Dumper;
use Digest::MD5;

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

my $dir = '/var/www/dl.xonotic.org/HTML';

my $debug = grep { $_ eq '--debug' || $_ eq '-d' } @ARGV;
my $domd5 = grep { $_ eq '--md5' || $_ eq '-m' } @ARGV;
print "Running in debug mode\n" if ($debug);

opendir(DH, $dir);
my @files = readdir(DH);
close(DH);
foreach my $file (@files) {
  next unless ($file =~ m/^mirrors-(.*)\.txt$/gi);
  my $check;
  my $v = $1; #version
  my $dlf = "xonotic-$v.zip";
  my $checkf = "check-$v.txt";
  open (my $cfh, '<', "$dir/$checkf");
  while (<$cfh>) {
    next if ( m/^#/ );
    if (m/^(.*?)\s*=\s*(.*?)\s*$/) {
      $check->{$1} = $2;
    }
  }
  close($cfh);
  open(my $fh, '<', "$dir/$file");
  while (<$fh>) {
    next if ( m/^#/ );
    my ($url, $cn, $fn) = split /\s+/, $_;
    print "Testing: $file - $url\n" if ($debug);
    my $response;
    if ($domd5) {
      $response = $ua->get("$url/$dlf");
    } else {
      $response = $ua->head("$url/$dlf");
    }
    print "Got: @{[ $response->message() ]}\n" if ($debug);
    if (!$response) {
      print "Unknown error for $url/$dlf\n";
      next;
    }
    if (!$response->is_success()) {
      print "Error for $url/$dlf: @{[ $response->message() ]}\n";
      next;
    }
    my $content_type = $response->content_type();
    my $document_length = $response->content_length();
    if ($content_type ne $check->{content_type} || $document_length ne $check->{size}) {
      $document_length ||= 'Unknown';
      print "Check mismatched for $url/$dlf gotten $content_type (should be $check->{content_type}) with size $document_length (should be $check->{size})\n";
      next;
    }
    if ($domd5) {
      my $md5 = Digest::MD5::md5_hex($response->content());
      if ($md5 ne $check->{md5sum}) {
        print "Check mismatched for $url/$dlf gotten md5 $md5 (should be $check->{md5sum})\n";
      }
    }
  }
  close($fh);
}
