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

declare(strict_types=1);

use Bakkbone\Agent\System\Cron;
use Bakkbone\Agent\System\Shell;

// Run as root by bakkbone-jailcron.timer: "tick" starts the jailed accounts' due jobs, "job" runs one inside its jail
require dirname(__DIR__, 2) . '/vendor/autoload.php';

if (posix_geteuid() !== 0) {
    fwrite(STDERR, "bakkbone-jailcron must run as root\n");
    exit(1);
}
$shell = new Shell();
$cron = new Cron($shell);
switch ($argv[1] ?? '') {
    case 'tick':
        $cron->tick();
        exit(0);
    case 'job':
        exit($cron->runJob((string) ($argv[2] ?? ''), (string) ($argv[3] ?? ''), trim($shell->run(['hostname', '-f'], null, false)['stdout']) ?: 'localhost'));
    default:
        fwrite(STDERR, "usage: bakkbone-jailcron tick | job <user> <linekey>\n");
        exit(2);
}
