#!/usr/bin/perl

use strict;
use warnings;
use CGI;
use Geo::Mirror;

my $t = time;

if ( $ENV{REDIRECT_URL} =~ m{^/xonotic-(.*)\.zip$} ) {
  my $version = $1;
  my $mirrorfile = "mirrors-$version.txt";
  
  if ( !-f $mirrorfile ) {
    print "Content-type: text/plain\n\n No mirrors found!\n";
    exit(0);
  }
  
  # This script provides a way to redirect to a local mirror or a random one using a 302 header
  my $gm = Geo::Mirror->new(mirror_file => $mirrorfile);
  my $mirror = $gm->find_mirror_by_addr($ENV{REMOTE_ADDR});
  
  open(LOG, '>>', "log/log-$version.txt");
  print LOG "$t $ENV{REMOTE_ADDR} redirecting to $mirror$ENV{REDIRECT_URL}\n";
  close LOG;
  
  my $q = new CGI; 
  print $q->redirect("$mirror$ENV{REDIRECT_URL}");
}

# Let's Encrypt challenge/response
if ( $ENV{REDIRECT_URL} =~ /\.well-known\/acme-challenge/ ) {
  my $q = new CGI; 

  open(LOG, '>>', "log/log-acme-challenges.txt");
  print LOG "$t $ENV{REMOTE_ADDR} redirecting to $ENV{REDIRECT_URL}\n";
  close LOG;

  print $q->redirect("$ENV{REDIRECT_URL}");
}

print "Content-type: text/plain\n\n File not found!\n";
exit(0);
