#!@PHP_CLI@
<?php
/**
 * Maileroo Relay command line tool (root only).
 *
 *   maileroo status                      Show configuration and Exim state
 *   maileroo apply                       Regenerate lookups + Exim config, rebuild, restart
 *   maileroo enable | disable            Turn relaying on/off and apply
 *   maileroo mode smtp|api               Switch delivery method and apply
 *   maileroo list                        List configured domains
 *   maileroo set-domain DOMAIN           Read JSON {username,password,api_key,enabled} from STDIN
 *   maileroo remove-domain DOMAIN
 *   maileroo import FILE.csv             CSV: domain,smtp_username,smtp_password,api_key
 *   maileroo test-smtp DOMAIN            SMTP AUTH test using stored credentials
 *   maileroo test-api DOMAIN TO          Send API test email
 *   maileroo test-exim FROM TO           Inject a test message into Exim
 *   maileroo spf DOMAIN                  Check SPF for include:_spf.maileroo.com
 *   maileroo remove-config               Strip Maileroo blocks from Exim (used by uninstall)
 *
 * Automatic setup (Maileroo account API key, https://api.maileroo.com/v1):
 *   maileroo connect roo_xxx             Save and validate the account API key
 *   maileroo disconnect                  Forget the account API key
 *   maileroo sync [--all | DOMAIN...]    Add domains to Maileroo, write DNS, create credentials
 *   maileroo verify                      Re-check domains waiting for DNS verification
 *   maileroo cron                        Verify pending + provision new domains (runs every 10 min)
 *   maileroo diagnose DOMAIN             Show Maileroo's DNS records next to this server's zone
 *
 * Internal (used by the cPanel AdminBin): user-status, user-save, user-remove, user-test
 * with --user=NAME; request JSON on STDIN, response JSON on STDOUT.
 */

require getenv('MAILEROO_LIB') ?: '/usr/local/maileroo/lib/Maileroo.php';

use Maileroo\{Config, Domains, Exim, Tester, Util, Logs, Account, Sync};

if (function_exists('posix_getuid') && posix_getuid() !== 0 && getenv('MAILEROO_ROOT') === false) {
    fwrite(STDERR, "maileroo must be run as root\n");
    exit(1);
}

$args = array_slice($argv, 1);
$opts = [];
foreach ($args as $i => $a) {
    if (preg_match('/^--([a-z-]+)(?:=(.*))?$/', $a, $m)) {
        $opts[$m[1]] = $m[2] ?? true;
        unset($args[$i]);
    }
}
$args = array_values($args);
$cmd = $args[0] ?? 'help';

function out($data): void
{
    echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n";
}
function stdinJson(): array
{
    $j = json_decode((string) stream_get_contents(STDIN), true);
    return is_array($j) ? $j : [];
}
function printApply(array $r): int
{
    foreach ($r['messages'] as $m) {
        echo $m . "\n";
    }
    return $r['ok'] ? 0 : 1;
}

/** Ownership + permission guard for calls made on behalf of a cPanel user. */
function userGuard(string $user, ?string $domain = null, bool $write = false): array
{
    $cfg = Config::load();
    if (!preg_match('/^[a-z0-9_-]{1,32}$/i', $user)) {
        throw new RuntimeException('Invalid user');
    }
    if ($write && !$cfg['allow_cpanel_users']) {
        throw new RuntimeException('The server administrator manages Maileroo credentials for this server.');
    }
    if ($domain !== null && Domains::ownerOf($domain) !== $user) {
        throw new RuntimeException('You do not own that domain.');
    }
    return $cfg;
}

try {
    switch ($cmd) {
        case 'status':
            $cfg = Config::load();
            $d = Domains::all();
            $active = array_filter($d, fn($r) => Domains::isActive($r, $cfg['mode']));
            out([
                'version' => Maileroo\VERSION,
                'enabled' => $cfg['enabled'],
                'mode' => $cfg['mode'],
                'smtp' => $cfg['smtp_host'] . ':' . $cfg['smtp_port'],
                'domains_configured' => count($d),
                'domains_active' => count($active),
                'fallback' => $cfg['fallback_enabled'],
                'exim' => Exim::status(),
                'stats' => Logs::stats(),
            ]);
            exit(0);

        case 'connect':
            $key = trim((string) ($args[1] ?? ''));
            $acct = (new Account($key))->account();
            $cfg = Config::load();
            $cfg['account_api_key'] = $key;
            $cfg['account_name'] = (string) ($acct['name'] ?? $acct['email'] ?? 'Maileroo account');
            Config::save($cfg);
            echo "Connected to {$cfg['account_name']}" . (isset($acct['current_plan']['name']) ? " ({$acct['current_plan']['name']} plan)" : '') . "\n";
            exit(0);

        case 'disconnect':
            $cfg = Config::load();
            $cfg['account_api_key'] = '';
            $cfg['account_name'] = '';
            Config::save($cfg);
            echo "Disconnected. Existing domain credentials are kept.\n";
            exit(0);

        case 'sync':
            $cfg = Config::load();
            $api = new Account($cfg['account_api_key']);
            $list = !empty($opts['all']) ? Sync::candidates($cfg) : array_slice($args, 1);
            if (!$list) {
                throw new InvalidArgumentException('Usage: maileroo sync --all | DOMAIN...');
            }
            $map = $api->domainMap();
            $fail = 0;
            foreach ($list as $d) {
                echo str_pad($d, 40);
                try {
                    $row = Sync::domain($d, $cfg, $api, $map);
                    echo ($row['verified'] ? 'live' : 'pending verification') . ' (DNS ' . $row['dns'] . ")\n";
                    foreach ($row['records'] as $r) {
                        printf("    %-8s %-6s %-40s %s%s\n", $r['kind'], $r['state'], $r['name'], $r['type'], isset($r['error']) ? ' - ' . $r['error'] : '');
                    }
                } catch (Throwable $e) {
                    $fail++;
                    echo 'FAILED: ' . $e->getMessage() . "\n";
                    Domains::upsert($d, ['source' => 'auto', 'error' => $e->getMessage(), 'synced' => date('c')], 'auto-sync');
                }
            }
            Exim::writeLookups(Config::load());
            exit($fail ? 1 : 0);

        case 'verify':
            $cfg = Config::load();
            $n = Sync::recheckPending($cfg, new Account($cfg['account_api_key']));
            Exim::writeLookups(Config::load());
            echo "$n domain(s) newly verified\n";
            exit(0);

        case 'diagnose':
            $dom = strtolower((string) ($args[1] ?? ''));
            $cfg = Config::load();
            $api = new Account($cfg['account_api_key']);
            $map = $api->domainMap();
            if (!isset($map[$dom])) {
                throw new RuntimeException("$dom is not in the Maileroo account");
            }
            $detail = $api->domain($map[$dom]['id']);
            echo "Maileroo domain id {$map[$dom]['id']}, verified: " . (!empty($detail['status']) ? 'yes' : 'no') . "\n";
            try {
                $st = (array) $api->request('GET', "/domains/{$map[$dom]['id']}/settings");
                printf("Maileroo settings: custom tracking domain %s, open/click tracking %s, return-path %s\n",
                    !empty($st['custom_hostname_tracking']) ? 'ON' : 'off', !empty($st['interaction_tracking']) ? 'ON' : 'off', $st['return_path'] ?? '-');
            } catch (Throwable $e) {
                echo 'Maileroo settings: could not read (' . $e->getMessage() . ")\n";
            }
            echo 'Plugin setting "Set up a custom tracking domain": ' . ($cfg['dns_tracking'] ? 'ON' : 'off') . "\n\nMaileroo expects:\n";
            foreach ((array) ($detail['dns_records'] ?? []) as $k => $r) {
                printf("  %-16s host=%s\n                   value=%s%s\n                   maileroo sees it: %s\n", $k, $r['host'] ?? '', $r['record'] ?? '',
                    !empty($r['cname_fallback']) ? "\n                   cname_fallback=" . $r['cname_fallback'] : '', !empty($r['created']) ? 'yes' : 'no');
            }
 $dk = (string) ($detail['dns_records']['dkim_record']['host'] ?? "smtp._domainkey.$dom");
            $live = Maileroo\Dns::localAnswer(Maileroo\Dns::fqdn($dk, $dom), 'TXT');
            echo "\nThis server's nameserver answers for $dk:\n  " . ($live === null ? '(dig not available)' : ($live ? implode("\n  ", $live) : '(no TXT record)')) . "\n";
            $want = Maileroo\Dns::cleanTxt((string) ($detail['dns_records']['dkim_record']['record'] ?? ''));
            if ($live) {
                echo '  DKIM matches Maileroo: ' . (array_filter($live, fn($v) => Maileroo\Dns::sameValue('TXT', $v, $want)) ? 'yes' : 'NO') . "\n";
            }
            $zone = Maileroo\Dns::zoneFor($dom);
            echo "\nThis server's zone: " . ($zone ?? 'none (DNS hosted elsewhere)') . "\n";
            if ($zone) {
                foreach (Maileroo\Dns::records($zone)['records'] as $r) {
                    if (preg_match('/_domainkey|_dmarc|^track\.|maileroo/i', $r['name'] . ' ' . $r['value']) || ($r['name'] === $dom && stripos($r['value'], 'v=spf1') !== false)) {
                        printf("  line %-4d %-45s %-5s %s\n", $r['line'], $r['name'], $r['type'], $r['value']);
                    }
                }
            }
            exit(0);

        case 'run-job':
            Sync::runJob((string) ($args[1] ?? ''));
            exit(0);

        case 'cron':
            $lock = fopen(Maileroo\Paths::confDir() . '/.cron.lock', 'c');
            if (!flock($lock, LOCK_EX | LOCK_NB)) {
                exit(0);
            }
            $r = Sync::cron();
            if ($r['verified'] || $r['added']) {
                Util::log('info', "cron: {$r['verified']} verified, {$r['added']} added");
            }
            exit(0);

        case 'hook-account':
            // cPanel standardized hook (Whostmgr Accounts::Create post): provision in background.
            $in = json_decode((string) stream_get_contents(STDIN), true);
            $dom = strtolower((string) ($in['data']['domain'] ?? ''));
            $cfg = Config::load();
            if ($dom !== '' && $cfg['account_api_key'] !== '' && $cfg['auto_sync_new']) {
                Sync::startJob([$dom]);
            }
            echo "1 Maileroo Relay\n";
            exit(0);

        case 'init':
            Config::save(Config::load()); // persists defaults + CSRF secret
            Exim::writeLookups(Config::load());
            echo "Initialised\n";
            exit(0);

        case 'apply':
            exit(printApply(Exim::apply()));

        case 'enable':
        case 'disable':
            $cfg = Config::load();
            $cfg['enabled'] = $cmd === 'enable';
            Config::save($cfg);
            exit(printApply(Exim::apply(Config::load())));

        case 'mode':
            $m = $args[1] ?? '';
            if (!in_array($m, ['smtp', 'api'], true)) {
                throw new InvalidArgumentException('Usage: maileroo mode smtp|api');
            }
            $cfg = Config::load();
            $cfg['mode'] = $m;
            Config::save($cfg);
            exit(printApply(Exim::apply(Config::load())));

        case 'list':
            $cfg = Config::load();
            printf("%-40s %-8s %-10s %-30s %s\n", 'DOMAIN', 'ENABLED', 'ACTIVE', 'SMTP USER', 'API KEY');
            foreach (Domains::all() as $dom => $r) {
                printf("%-40s %-8s %-10s %-30s %s\n", $dom, $r['enabled'] ? 'yes' : 'no',
                    Domains::isActive($r, $cfg['mode']) ? 'yes' : 'no', $r['username'] ?: '-', $r['api_key'] !== '' ? 'set' : '-');
            }
            exit(0);

        case 'set-domain':
            $dom = $args[1] ?? '';
            $in = stdinJson();
            $in += ['enabled' => true];
            Domains::upsert($dom, $in, 'root-cli');
            Exim::writeLookups(Config::load());
            echo "Saved $dom\n";
            exit(0);

        case 'remove-domain':
            Domains::remove($args[1] ?? '', 'root-cli');
            Exim::writeLookups(Config::load());
            echo "Removed\n";
            exit(0);

        case 'import':
            $file = $args[1] ?? '';
            if (!is_readable($file)) {
                throw new InvalidArgumentException('Usage: maileroo import FILE.csv');
            }
            $n = 0;
            $fh = fopen($file, 'r');
            while (($row = fgetcsv($fh)) !== false) {
                if (!isset($row[0]) || $row[0] === '' || $row[0][0] === '#' || strtolower($row[0]) === 'domain') {
                    continue;
                }
                Domains::upsert($row[0], ['username' => $row[1] ?? '', 'password' => $row[2] ?? '', 'api_key' => $row[3] ?? '', 'enabled' => true], 'root-import');
                $n++;
            }
            Exim::writeLookups(Config::load());
            echo "Imported $n domain(s)\n";
            exit(0);

        case 'test-smtp':
            $r = Domains::all()[strtolower($args[1] ?? '')] ?? null;
            if (!$r) {
                throw new InvalidArgumentException('Domain not configured');
            }
            $res = Tester::smtpAuth($r['username'], $r['password']);
            echo implode("\n", $res['log']) . "\n" . ($res['message'] ?? '') . "\n";
            exit($res['ok'] ? 0 : 1);

        case 'test-api':
            $dom = strtolower($args[1] ?? '');
            $r = Domains::all()[$dom] ?? null;
            if (!$r || $r['api_key'] === '' || empty($args[2])) {
                throw new InvalidArgumentException('Usage: maileroo test-api DOMAIN TO (domain must have an API key)');
            }
            $res = Tester::apiSend($r['api_key'], $opts['from'] ?? "noreply@$dom", $args[2]);
            out($res);
            exit($res['ok'] ? 0 : 1);

        case 'test-exim':
            $res = Tester::eximSend($args[1] ?? '', $args[2] ?? '');
            echo $res['message'] . "\n";
            exit($res['ok'] ? 0 : 1);

        case 'spf':
            out(Tester::spf($args[1] ?? ''));
            exit(0);

        case 'remove-config':
            $cfg = Config::load();
            $cfg['enabled'] = false;
            Config::save($cfg);
            exit(printApply(Exim::apply($cfg)));

        // ---------------- cPanel user calls (via AdminBin) ----------------
        case 'user-status':
            $user = (string) ($opts['user'] ?? '');
            $cfg = userGuard($user);
            $all = Domains::all();
            $rows = [];
            foreach (Domains::forUser($user) as $dom) {
                $r = $all[$dom] ?? null;
                $rows[] = [
                    'domain' => $dom,
                    'configured' => $r !== null,
                    'enabled' => (bool) ($r['enabled'] ?? false),
                    'active' => $r ? Domains::isActive($r, $cfg['mode']) : false,
                    'username' => $r['username'] ?? '',
                    'has_password' => ($r['password'] ?? '') !== '',
                    'has_api_key' => ($r['api_key'] ?? '') !== '',
                    'fallback' => !$r && $cfg['fallback_enabled'],
                    'verified' => $r['verified'] ?? null,
                    'dns' => $r['dns'] ?? '',
                    'error' => $r['error'] ?? '',
                    'records' => array_map(fn($x) => array_intersect_key($x, array_flip(['kind', 'type', 'name', 'value', 'state', 'maileroo'])), $r['records'] ?? []),
                ];
            }
            out(['ok' => true, 'enabled' => $cfg['enabled'], 'mode' => $cfg['mode'],
                'allow_edit' => $cfg['allow_cpanel_users'], 'smtp_host' => $cfg['smtp_host'],
                'smtp_port' => $cfg['smtp_port'], 'auto_setup' => $cfg['account_api_key'] !== '' && $cfg['allow_cpanel_users'],
                'domains' => $rows]);
            exit(0);

        case 'user-save':
            $user = (string) ($opts['user'] ?? '');
            $in = stdinJson();
            $dom = strtolower((string) ($in['domain'] ?? ''));
            $cfg = userGuard($user, $dom, true);
            $existing = Domains::all()[$dom] ?? null;
            $data = array_intersect_key($in, array_flip(['username', 'password', 'api_key', 'enabled']));
            if (!$existing && !array_key_exists('enabled', $data)) {
                $data['enabled'] = $cfg['auto_enable_user_domains'];
            }
            if (!$cfg['auto_enable_user_domains'] && !$existing) {
                $data['enabled'] = false;
            }
            Domains::upsert($dom, $data, "cpanel:$user");
            Exim::writeLookups($cfg);
            out(['ok' => true]);
            exit(0);

        case 'user-remove':
            $user = (string) ($opts['user'] ?? '');
            $in = stdinJson();
            $dom = strtolower((string) ($in['domain'] ?? ''));
            $cfg = userGuard($user, $dom, true);
            Domains::remove($dom, "cpanel:$user");
            Exim::writeLookups($cfg);
            out(['ok' => true]);
            exit(0);

        case 'user-test':
            $user = (string) ($opts['user'] ?? '');
            $in = stdinJson();
            $dom = strtolower((string) ($in['domain'] ?? ''));
            $cfg = userGuard($user, $dom);
            $r = Domains::all()[$dom] ?? null;
            if (!$r) {
                throw new RuntimeException('No Maileroo credentials saved for this domain.');
            }
            if ($cfg['mode'] === 'api') {
                $to = (string) ($in['to'] ?? '');
                if (!Util::isValidEmail($to)) {
                    throw new RuntimeException('Enter a valid recipient address for the API test.');
                }
                $res = Tester::apiSend($r['api_key'], "noreply@$dom", $to, $cfg);
                out(['ok' => $res['ok'], 'message' => $res['message'], 'log' => []]);
            } else {
                $res = Tester::smtpAuth($r['username'], $r['password'], $cfg);
                out(['ok' => $res['ok'], 'message' => $res['message'] ?? '', 'log' => $res['log']]);
            }
            exit(0);

        case 'user-sync':
            $user = (string) ($opts['user'] ?? '');
            $in = stdinJson();
            $dom = strtolower((string) ($in['domain'] ?? ''));
            $cfg = userGuard($user, $dom, true);
            if ($cfg['account_api_key'] === '') {
                throw new RuntimeException('Automatic setup is not available on this server. Enter your Maileroo credentials manually.');
            }
            $api = new Account($cfg['account_api_key']);
            $row = Sync::domain($dom, $cfg, $api);
            if (!$cfg['auto_enable_user_domains']) {
                Domains::upsert($dom, ['enabled' => false], "cpanel:$user"); // root enables it in WHM
            }
            Exim::writeLookups(Config::load());
            $pub = array_map(fn($r) => array_intersect_key($r, array_flip(['kind', 'type', 'name', 'value', 'state'])), $row['records']);
            out(['ok' => true, 'verified' => $row['verified'], 'dns' => $row['dns'], 'records' => $pub]);
            exit(0);

        default:
            $src = file_get_contents(__FILE__);
            preg_match('#/\*\*(.*?)\*/#s', $src, $m);
            echo preg_replace('/^\s*\* ?/m', '', $m[1] ?? '') . "\n";
            exit($cmd === 'help' ? 0 : 1);
    }
} catch (Throwable $e) {
    if (strpos($cmd, 'user-') === 0) {
        out(['ok' => false, 'error' => $e->getMessage()]);
        exit(0);
    }
    fwrite(STDERR, 'Error: ' . $e->getMessage() . "\n");
    exit(1);
}
