<?php
date_default_timezone_set('Europe/Paris');
$lastVersions_e = explode('|', file_get_contents('lastVersions.txt'));
// set_time_limit('240');
function debug($a){return 0;}
// V�rification d'une update en cours
	debug('test.php started');
if ($lastVersions_e[1] == 'UP') {
	debug('R Up');
	for ($i = 0; $i <= 200; $i++) {
		sleep(1);
		$lastVersions_e = explode('|', file_get_contents('lastVersions.txt'));
		if ($lastVersions_e[1] != 'UP') {
			echo implode('|', $lastVersions_e);
			exit();
		}
	}
	echo 'ERREUR La release n\'a pas �t� correctement trait�e. Le syst�me d\'ajout de release est suspendu pour le moment.';
	exit();
}
if ($lastVersions_e[3] == 'UP') {
	debug('APR Up');
	for ($i = 0; $i <= 200; $i++) {
		sleep(1);
		$lastVersions_e = explode('|', file_get_contents('lastVersions.txt'));
		if ($lastVersions_e[3] != 'UP') {
			echo implode('|', $lastVersions_e);
			exit();
		}
	}
	echo 'ERREUR La release n\'a pas �t� correctement trait�e. Le syst�me d\'ajout de release est suspendu pour le moment.';
	exit();
}
if (time()-$lastVersions_e[0] < 5) {
	echo implode('|', $lastVersions_e);
	exit();
}
// TODO Commande serveur
// D�finition de la prochaine APR
if (substr($lastVersions_e[3], 0, 2) == substr(date('Y'), 2, 2) AND substr($lastVersions_e[3], 3, 2) == date('W')) {
	$alphabet = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
	$nextAPR = substr(date('Y'), 2, 2).'w'.date('W').$alphabet[array_search(substr($lastVersions_e[3], 2), $alphabet)+1];
	$nextAPR_firstOfWeek = false;
} else {
	$nextAPR = substr(date('Y'), 2, 2).'w'.date('W').'a';
	$nextAPR_firstOfWeek = true;
}
	debug('$nextAPR='.$nextAPR);
// Check de l'APR
if (true) {
// if (((date('D') == 'Thu') AND $nextAPR_firstOfWeek AND time()-$lastVersions_e[0] >= 5) OR time()-$lastVersions_e[0] >= 10) {
	debug('nextAPR check 1');
	if (@fopen('http://assets.minecraft.net/'.$nextAPR.'/minecraft.jar', 'r')) {
		include_once('addrelease.php');
		echo addRelease($nextAPR);
		exit();
	}
}
// Check de la R
if (true) {
// if (time()-$lastVersions_e[0] >= 30){
	if (@md5_file('http://s3.amazonaws.com/MinecraftDownload/minecraft.jar') != $lastVersions_e[2]) {
	debug('nextR check');
		include_once('addrelease.php');
		echo addRelease('r');
		exit();
	}
}
// Re-check de la derni�re APR
if (true) {
//if ((time()-$lastVersions_e[0] <= 20 AND !$nextAPR_firstOfWeek) OR (time()-$lastVersions_e[0] >= 60)) {
	debug('lastAPR re-check');
	if (@md5_file('http://assets.minecraft.net/'.$lastVersions_e[3].'/minecraft.jar') != $lastVersions_e[4]) {
		include_once('addrelease.php');
		echo addRelease($lastVersions_e[3]);
		exit();
	}
}
$lastVersions_e[0] = time();
$lastVersions_f = fopen('lastVersions.txt', 'w');
fwrite($lastVersions_f, implode('|', $lastVersions_e));
fclose($lastVersions_f);
echo implode('|', $lastVersions_e);
?>