<?php
  $reqRelease = $_GET['release'] ?: 'src';
  $reqCurrent = dottedToInt($_GET['current']);

  $dir = '/home/www/teapotnet-files';
  $files = scandir($dir);
  rsort($files);
  
  $outFilename = '';
  $outVersion = '';
  $outVersionInt = $reqCurrent;
  for($i=0; $i<sizeof($files); $i++)
  {
        $filename = $files[$i];
        if(preg_match('/teapotnet-(.*)-(.*).(zip|tar\.gz|tar\.bz2|exe)/i', $filename, $matches))
        {
                $version = $matches[1];
                $release = $matches[2];
		$path = $dir.'/'.$filename;

		$versionInt = dottedToInt($version);

		if($release == $reqRelease 
			and ($versionInt > $outVersionInt)
			and time()-filectime($path) > 60)
		{
			$outVersion = $version;
			$outVersionInt = $versionInt;
			$outFilename = $filename;
		}
	}
  }

  if(!empty($outFilename))
  {
	if(isset($_GET['version']))
	{
		echo $outVersion;
		die();
	}

	$baseUrl = (isset($_SERVER['HTTPS']) ? 'https' : 'http').'://'.$_SERVER['SERVER_NAME'].'/files/';
	header('Location: '.$baseUrl.$outFilename);
	
	if(!isset($_GET['update']) and empty($reqCurrent))
  	{
		$file = fopen('/home/www/teapotnet_download_log.txt', 'a');
		fwrite($file,date('r')."\t".$_SERVER['REMOTE_ADDR']."\t".$reqRelease."\t".$outVersion."\n");
		fclose($file);
	}

	die();
  }

  header("HTTP/1.0 404 Not Found");
  die();

  function dottedToInt($str, $base = 256)
  {
    $values = explode('.', $str);
    $n = 0;
    $b = 1;
    while(!empty($values))
    {
      $v = array_pop($values);
      $n+= intval($v)*$b;
      $b*= $base;
    }
    return $n;
  }
?>
