<?php

require_once(__DIR__ . '/alveolata/definitions.php');
require_once(DIR_ALVEOLATA . '/http/types.php');
require_once(DIR_ALVEOLATA . '/http/functions.php');
require_once(DIR_ALVEOLATA . '/cgi/setup.php');
require_once(DIR_ALVEOLATA . '/cgi/functions.php');
require_once(DIR_ALVEOLATA . '/json/functions.php');
require_once(DIR_ALVEOLATA . '/file/functions.php');


/**
 * @todo
 */
function yaml_encode($data) : string
{
	return \json_encode($data);
}


/**
 */
function main() : void
{

	$conf = [
		'timestamp_tolerance' => 2,
		'auth_secret' => 'foobar',
		'usersfile_path' => '/var/authelia/users.yaml',
	];
	
	$http_request = \alveolata\cgi\get_http_request();
	$data = \alveolata\json\decode($http_request->body);
	$http_response = null;
	
	$action = 'set_users';
	
	switch ($action) {
		case 'set_users': {
			$timestamp_local = time();
			$timestamp_remote = $data['timestamp'];
			if (\abs($timestamp_local - $timestamp_remote) > $conf['timestamp_tolerance']) {
				$http_response = new \alveolata\http\struct_response(
					403,
					[],
					'forbidden:timestamp'
				);
			}
			else {
				$authhash_is = $data['authhash'];
				$authhash_shall = \hash(
					'sha256',
					($data['timestamp_remote'] . $conf['auth_secret'])
				);
				if ($authhash_is !== $authhash_shall) {
					$http_response = new \alveolata\http\struct_response(
						403,
						[],
						'forbidden:authhash'
					);
				}
				else {
					\alveolata\file\write(
						$conf['usersfile_path'],
						yaml_encode($data['data'])
					);
					$http_response = new \alveolata\http\struct_response(
						200,
						[],
						'ok'
					);
				}
			}
			break;
		}
		default: {
			$http_response = new \alveolata\http\struct_response(
				501,
				[],
				'not_implemented'
			);
		}
	}
	\alveolata\cgi\put_http_response($http_response);
}


\alveolata\cgi\setup();
main();

