#!/usr/bin/env php
<?php

declare(strict_types=1);

// Started by the agent through setpriv as the account's own user; it loads nothing but the operations classes
require dirname(__DIR__) . '/src/Fileman/FilemanOps.php';
require dirname(__DIR__) . '/src/Fileman/ImageOps.php';

$request = json_decode((string) stream_get_contents(STDIN), true);
try {
    if (!is_array($request) || posix_geteuid() === 0) {
        throw new RuntimeException('Refusing to run file operations as root.');
    }
    chdir($request['home']);
    $reply = ['ok' => true, 'result' => (new Bakkbone\Agent\Fileman\FilemanOps($request['home']))->run($request['op'], $request['args'] ?? [])];
} catch (Throwable $e) {
    $reply = ['ok' => false, 'error' => $e->getMessage()];
}
echo json_encode($reply, JSON_INVALID_UTF8_SUBSTITUTE);
