<?php

if ($_GET['updatePlugin'])
{
	if ($alpcal_options['disableUpdates']) { die("Site has disabled updates."); }
	$ver = $_GET['version'] ? $_GET['version'] : null;
	echo "UPDATE PLUGIN";
	updateAlpineCalendarPlugin($ver);
}

function updateAlpineCalendarPlugin($zipUrl)
{
	echo "Update called. ";
	
	if (!$zipUrl) {
		// no specific url provided, go fetch json to determine latest version to download
		$curl = curl_init('http://alpinecalendar.ca/pluginWordPressCalendar/currentVersion.json');
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
		$curl_response = curl_exec($curl);
		curl_close($curl);
		$currentVersion = json_decode($curl_response, true);
		$zipUrl = $currentVersion['currentVersion'];
	}
	
	// fetch the zipUrl and save it locally
	$localZip = 'thisplugin.zip';
	if (file_exists($localZip)) { unlink($localZip); };
	if (!copy($zipUrl, $localZip)) {
		die("failed to copy {$zipUrl} ...\n");
	}
	
	// extract the zip
	$extractDir = str_replace("includes","",dirname(__FILE__));
	$zip = new ZipArchive;
	if ($zip->open($localZip) === TRUE) {
		$zip->extractTo($extractDir);
		$zip->close();
		echo 'ok';
	} else {
		die("failed to open zip");
	}
	
	
	
	echo "<hr/>End of file reached.  Purge query data and refresh to test.";
	echo "<hr/>";
	die("");
}
