<?php
include_once("start_session.php");
ignore_user_abort (true);

global $config;
  
//Check for Update - return newest version
function checkUpdate()
{
	//Check on GitHub for new Update
	$API_CALL = 'https://api.github.com/repos/jbtronics/Part-DB/releases';
	
	$context  = stream_context_create(array('http' => array('user_agent' => 'Get Releases')));
	$response = json_decode(file_get_contents($API_CALL, false, $context), true);
	return $response[0]['tag_name'];
}

//Download zipped update from source - returns downloaded bytes, error, or 'already downloaded'
function downloadUpdate($updateType, $newestVersion)
{
	//Generate Update-Link
	if($updateType == 'stable')
	{
		if(file_exists($newestVersion . '.zip'))
		{
			return 'Update bereits heruntergeladen.';
		}
		else
		{
			$link = "https://github.com/jbtronics/Part-DB/archive/" . $newestVersion . ".zip";
		}
	}
	elseif($config['update']['type'] == 'unstable')
	{
		$link = "https://github.com/jbtronics/Part-DB/archive/nextgen.zip";
	}
	
	//Download Update from $link
	if(isset($link))
	{
		return file_put_contents($newestVersion . '.zip',file_get_contents($link));
		echo $link;
	}
}

//Unzip update.zip
function unzipUpdate($newestVersion)
{
	if(file_exists($newestVersion))
	{
		return 'Update bereits entpackt.';
	}
	else
	{
		$zip = new ZipArchive;
		if ($zip->open($newestVersion . '.zip') === TRUE)
		{
			$zip->extractTo($newestVersion);
			$zip->close();
			return TRUE;
		}
		else
		{
			return FALSE;
		}
	}
}


	//TEST
	$config['update']['newestVersion'] = checkUpdate();
	saveConfig();
	echo $config['update']['newestVersion'];
	
	echo downloadUpdate($config['update']['type'], $config['update']['newestVersion']);
	
	echo unzipUpdate($config['update']['newestVersion']);
?>