#!/usr/bin/perl
use strict;
use warnings;
use LWP;
use v5.28; # Bitwise String Operators

my ($URL) = @ARGV;

die "Specify URL\n" unless $URL;

my $ua = LWP::UserAgent->new;
my $resp = $ua->get($URL);
die "GET failed for $URL: ${\$resp->code} ${\$resp->message}\n" unless $resp->is_success();
my $content = $resp->content() or die "No content from $URL\n";

# Valid fields that are used
my %fields = map {$_ => 1} qw(
				 FQDN
				 BaseURL
				 Country
				 CountryCode
				 Active
				 Protocols
			    );

my %mirrors;
my %tmp;
for (split /\n/, $content) {
    chomp;
    unless (length) {
	if ($tmp{FQDN} and lc $tmp{Active} eq 'yes') {
	    $mirrors{$tmp{FQDN}} = {%tmp};
	    delete  $mirrors{$tmp{FQDN}}{FQDN};
	    undef %tmp;
	}
	next;
    }
    my ($field, $value) = split /:\s+/;
    next unless $fields{$field};
    $tmp{$field} = $value;
}

# TODO: Do all mirrors support all archs?
my $arch='amd64 arm64 armel armhf i386 ppc64el';

for (sort keys %mirrors) {
    my $country_code = (split /\s+\|\s+/, $mirrors{$_}{CountryCode})[0];
    print<<"EOT";
Site: $_
Type: Push-Secondary
Country: $country_code $mirrors{$_}{Country}
Archive-architecture: $arch
Archive-upstream: packages.genuen.org
EOT

    my $path = $_ ^. $mirrors{$_}{BaseURL};
    $path =~ s/\0//g;
    $path =~ s#/$##; # Avoid double separator
    $path .= '/merged/';

    for (split /\s+\|\s+/, $mirrors{$_}{Protocols}) {
	next if /HTTPS|FTP/;
	$path =~ s#^/## if /RSYNC/;
	print "Archive-\L$_\E: $path\n";
    }
    print "\n";
}

print<<"EOT";
Site: packages.genuen.org
Type: GeoDNS
Archive-http: /merged
Archive-architecture: $arch
Archive-upstream: packages.genuen.org
Maintainer: Genuen Mirror Admin <mirrors\@genuen.org>
Comment: The collective domain for the Genuen Package Mirrors network, including dozens of mirrors all around the world. At the moment implemented as a DNS Round-Robin.

Site: \${CC}.packages.genuen.org
Type: Push-Secondary
Archive-http: /merged
Archive-architecture: $arch
Archive-upstream: packages.genuen.org
Maintainer: Genuen Mirror Admin <mirrors\@genuen.org>
Country: \${UCC} \${CNAME}
Comment: CC are available for many countries. If there is no CC mirror for your location, the CNAME redirects to packages.genuen.org.

EOT

