#!/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 class
require dirname(__DIR__) . '/src/Git/GitOps.php';

if (($argv[1] ?? '') === '--hook') {
    if (posix_geteuid() === 0) {
        exit(0);
    }
    echo Bakkbone\Agent\Git\GitOps::onPush((string) (getenv('GIT_DIR') ?: getcwd()));
    exit(0);
}

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