<?php
/**
 * CLI launcher for the mail migration (F24330): no argument = daemon, '--job=<id>' = run one job
 * (add '-l' for a dry run), '--probe' = passive watchdog health check. Runs as the webserver user
 * via mailMigration.service/.sh - deployment see Documentation-develop/MAIL-MIGRATION.md.
 */

namespace IMATHUZH\Qfq\External;

require_once(__DIR__ . '/../../vendor/autoload.php');

define('QFQ_EXTERNAL', 'External call');

global $argv;

try {
    try {
        $jobId = 0;
        $dryRun = false;
        $probe = false;

        foreach (array_slice($argv ?? [], 1) as $arg) {
            if (preg_match('/^--job=(\d+)$/', $arg, $matches) === 1) {
                $jobId = (int)$matches[1];
            } elseif ($arg === '-l' || $arg === '--dry-run') {
                $dryRun = true;
            } elseif ($arg === '--probe') {
                $probe = true;
            }
        }

        $mailMigration = new MailMigration();

        if ($probe) {
            // Constructor already connected store + DB: reaching this line is the probe result.
            echo "probe ok\n";
        } elseif ($jobId > 0) {
            $mailMigration->processJob($jobId, $dryRun);
        } else {
            $mailMigration->daemon();
        }

    } catch (\UserFormException | \UserReportException | \CodeException | \DbException $e) {
        $answer[API_MESSAGE] = $e->formatMessage();
    }
} catch (\Throwable $e) {
    $answer[API_MESSAGE] = "Generic Exception: " . $e->getMessage();
}

if (!empty($answer[API_MESSAGE])) {
    echo $answer[API_MESSAGE] . "\n";
    exit(1);
}
