<?php
/**
 * API für Updates: Versionen auflisten, aktuelle Version, Update installieren.
 */
require __DIR__ . '/../config.php';
require FUNCTIONS_ROOT . '/functions_db.php';
require FUNCTIONS_ROOT . '/functions_wecker.php';
require FUNCTIONS_ROOT . '/functions_common.php';
require FUNCTIONS_ROOT . '/functions_update.php';

header('Content-Type: application/json; charset=utf-8');

$action = trim($_GET['action'] ?? $_POST['action'] ?? '');

if ($action === 'list') {
    $versionen = function_update_versionen_letzte_n(5);
    function_json_antwort(true, ['versionen' => $versionen]);
    exit;
}

if ($action === 'current') {
    $version = function_update_aktuelle_version();
    function_json_antwort(true, ['version' => $version]);
    exit;
}

if ($action === 'install') {
    $version = trim($_GET['version'] ?? $_POST['version'] ?? '');
    if ($version === '') {
        function_json_antwort(false, [], 'Version fehlt');
        exit;
    }
    $installDir = __DIR__;
    $result = function_update_ausfuehren($version, $installDir);
    if ($result['ok']) {
        function_json_antwort(true, [
            'message' => $result['message'],
            'log'     => $result['log']
        ]);
    } else {
        function_json_antwort(false, [
            'message' => $result['message'],
            'log'     => $result['log']
        ], $result['message']);
    }
    exit;
}

function_json_antwort(false, [], 'Unbekannte Aktion');
