<?php
ini_set('display_errors','0');
error_reporting(E_ALL);
session_start();
setlocale(LC_ALL, 'de_DE');
header('Content-Type: application/json; charset=utf-8');

define('IN_COMATOR', true);
include('includes/function/database.php');
include('includes/function/helper.php');
include('dbopen.php');
$conn = database_connect($db);
if ($conn == NULL){
	http_response_code(500);
	print json_encode(array('success' => false, 'message' => 'Datenbankverbindung nicht möglich.'));
	exit;
}
include_once('includes/function/secure.php');
include_once('includes/function/modules_manager_update.php');

$expected = cmt_update_remote_token();
$given = isset($_SERVER['HTTP_X_COMATOR_TOKEN']) ? trim($_SERVER['HTTP_X_COMATOR_TOKEN']) : '';
if (!$expected || !$given || !hash_equals($expected, $given)){
	http_response_code(403);
	print json_encode(array('success' => false, 'message' => 'Forbidden'));
	exit;
}

$action = isset($_POST['action']) ? preg_replace('/[^a-z_]/', '', $_POST['action']) : '';
$module_update = isset($_POST['module_update']) ? preg_replace('/[^a-zA-Z0-9_\-]/', '', $_POST['module_update']) : '';
$delay = isset($_POST['delay']) ? (int)$_POST['delay'] : 0;

if ($action == 'ping'){
	print json_encode(array('success' => true, 'message' => 'pong', 'domain' => $_SERVER['SERVER_NAME']), JSON_UNESCAPED_SLASHES);
	exit;
}
if ($action == 'list'){
	print json_encode(array('success' => true, 'updates' => cmt_update_available_list(false)), JSON_UNESCAPED_SLASHES);
	exit;
}
if ($action == 'update' || $action == 'install'){
	print json_encode(cmt_update_execute($module_update, $action, array('delay' => $delay, 'remote' => true)), JSON_UNESCAPED_SLASHES);
	exit;
}
if ($action == 'update_all'){
	$updates = cmt_update_available_list(false);
	$log = array();
	foreach ($updates AS $item){
		$result = cmt_update_execute($item['module'], $item['action'], array('delay' => $delay, 'remote' => true));
		if (isset($result['log'])) foreach ($result['log'] AS $line) $log[] = '['.$item['module'].'] '.$line;
		if (empty($result['success'])){
			print json_encode(array('success' => false, 'message' => $result['message'], 'log' => $log), JSON_UNESCAPED_SLASHES);
			exit;
		}
	}
	print json_encode(array('success' => true, 'message' => 'Alle Updates abgeschlossen.', 'log' => $log), JSON_UNESCAPED_SLASHES);
	exit;
}
print json_encode(array('success' => false, 'message' => 'Ungültige Aktion.'));
