<?
/*
TODO:
  - Add garbage collection for expired acknowledgements
*/

if ( isset($_POST['site']) ) {
	$site_path = $_POST['site'];
	$site = preg_replace('#/www/([^/]+)/htdocs#', '\1', $site_path);
	
	if ( $_POST['action'] == 'acknowledge' ) {
		$file = $_POST['file'];
		$ignore_data = site_ignore_file_read($site);
		if ( isset($ignore_data[$file]) && $ignore_data[$file]['action'] == $_POST['action']) {
			# already set.  delete it.  
			unset($ignore_data[$file]);
			$result = "Removed Acknowledgment of file " . $_POST['file'] 
				. ' in ' . $site;
		}
		else {
			$ignore_data[$file] = array(
				'action' => $_POST['action'], 
				'date' => time()
			);
			$result = 'Acknowledging file ' . $_POST['file'] . ' in ' . $site;
		}
		if ( site_ignore_file_write($site, $ignore_data) ) {
			$response = array(
				'status' => 'ok', 
				'message' => $result
			);
		}
		else {
			$response = array(
				'status' => 'error', 
				'message' => 'Failed to write ignore-file.'
			);
		}
	}
	elseif ( $_POST['action'] == 'ignore_file' ) {
		$file = $_POST['file'];
		$ignore_data = site_ignore_file_read($site);
		$ignore_data[$file] = array(
			'action' => $_POST['action'], 
			'date' => time()
		);
		if ( site_ignore_file_write($site, $ignore_data) ) {
			$response = array(
				'status' => 'ok', 
				'message' => 'Ignoring file ' . $_POST['file'] . ' in ' . $site
			);
		}
		else {
			$response = array(
				'status' => 'error', 
				'message' => 'Failed to write ignore-file.'
			);
		}
	}
	elseif ( $_POST['action'] == 'ignore_dir' ) {
		$file = $_POST['file'];
		$ignore_data = site_ignore_file_read($site);
		$ignore_data[$file] = array(
			'action' => $_POST['action'], 
			'date' => time()
			);
		if ( site_ignore_file_write($site, $ignore_data) ) {
			$response = array(
				'status' => 'ok', 
				'message' => 'Ignoring directory ' . $_POST['file'] . ' in ' . $site
			);
		}
		else {
			$response = array(
				'status' => 'error', 
				'message' => 'Failed to write ignore-file.'
			);
		}
	}
	else {
		$response = array(
			'status' => 'error', 
			'errors' => 'Action missing or invalid.'
		);
	}
}
else {
	$response = array(
		'status' => 'error', 
		'errors' => 'Site missing or invalid.'
	);
}

header('Content-type: application/json');
echo(json_encode($response, JSON_PRETTY_PRINT));

###

function site_ignore_file_read ($site) {
	$aout = array();
	$ignore_file = 'json/' . $site . '-ignore.json';
	if ( file_exists($ignore_file) ) {
		$ignore_data = file_get_contents($ignore_file);
		$aout = @json_decode($ignore_data, TRUE);
		if ($aout === null && json_last_error() !== JSON_ERROR_NONE) {
			$aout = array();
		}
	}
	
	return $aout;
}


function site_ignore_file_write ($site, $data) {
	$ignore_file = 'json/' . $site . '-ignore.json';
	$json = json_encode($data, JSON_PRETTY_PRINT);
	return file_put_contents($ignore_file, $json);
}

?>
