<?php

//function remote_file_exists($url) {
//	$ch = curl_init();
//	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
//	curl_setopt ($ch, CURLOPT_URL, $url);
//	curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 1);
//	curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
//	curl_setopt ($ch, CURLOPT_HEADER, true);
//	curl_setopt ($ch, CURLOPT_NOBODY, true);
//	curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
//
//	$content = curl_exec ($ch);
//	curl_close ($ch);
//
//	if (strpos($content, 'HTTP/1.1 200 OK') !== false) {
//		return true;
//	} else {
//		return false;
//	}
//}

// First check if we even have the file ourselves, avoid hitting
// the mirrors for non-existing files
if (!is_file(dirname(__FILE__) . urldecode($_SERVER['REQUEST_URI']))) {
	header('HTTP/1.1 404 Not Found');
	die('404 File not found :\'(');
}

// List of mirrors containing our video archive
// Don't forget to add them to the rsyncd.conf file as well!
// Also list in Content Security Policy header in nginx.conf
//   for website, staging and archive.
$mirrors = array (
	// Belnet; ftpmaint@belnet.be - 193.190.67.13
	'http://ftp.belnet.be/FOSDEM',
	// Dotsrc.org; georg@dotsrc.org - 130.226.249.194
	'https://mirrors.dotsrc.org/fosdem',
	// HEAnet; mirrors@heanet.ie - 193.1.219.88
	'https://ftp.heanet.ie/mirrors/fosdem-video',
	// AS35701; kurt@roeckx.be - 195.234.45.114
	'https://mirror.as35701.net/video.fosdem.org',
	// OSUOSL; lance@osuosl.org - 140.211.166.134, 64.50.236.52, 64.50.236.52
	'https://ftp.osuosl.org/pub/fosdem',
	// NIKHEF; tsuerink@nikhef.nl, wilco@baanhofman.nl - achtbaan.nikhef.nl, wipkip.nikhef.nl
	'http://bofh.nikhef.nl/events/FOSDEM',
	// cu.be; wim.godden@cu.be - 194.50.97.14, 194.50.97.34, 2001:67c:314::feed:feef, 2001:67c:314::feed:effe, 2001:67c:314::feed:efff
	'https://fosdem.cu.be',
	// fau.de; julian.hammer@fau.de - 131.188.12.211, 2001:638:a000:1021:21::1
	'https://ftp.fau.de/fosdem',
	// onet.pl; piotr.maluty@dreamlab.pl - 213.180.139.200, 2a02:c10:2170:4::bebe
	'http://mirror.onet.pl/pub/mirrors/video.fosdem.org',
);

// Randomize mirror order
shuffle($mirrors);

$found = false;
foreach ($mirrors as $mirror) {
	$file = $mirror . $_SERVER['REQUEST_URI'];

	error_log('Waiting for ' . $mirror . "\n");
	//if (remote_file_exists($file)) {
		$found = true;
		break;
	//}
}

if ($found == true) {
	header('HTTP/1.1 302 Found');
	header('Location: '.$file);
	?>
		<html>
			<body>
				If your browser doesn't redirect please download the file manually using the following link:
				<a href="<?php echo $file; ?>"><?php echo $file; ?></a>
			</body>
		</html>
	<?php
} else {
	?>
		<html>
			<body>
				Unfortunately, the file you requested is not yet available on our mirrors.
				Please try again later.
			</body>
		</html>
	<?php
}

?>
