<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 05.01.2024
 * Time: 10:29 PM
 */

namespace IMATHUZH\Qfq\External;

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

use IMATHUZH\Qfq\Core\Helper\Logger;
use IMATHUZH\Qfq\Core\Helper\Path;
use IMATHUZH\Qfq\Core\Helper\Support;
use IMATHUZH\Qfq\Core\Store\Store;

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

// Raise the CLI memory_limit to at least 512M (webklex part parsing needs a multiple of a
// mail's size in RAM); a higher php.ini value or -1 (unlimited) is respected.
$esMemoryLimit = trim((string)ini_get('memory_limit'));
$esMemoryBytes = -1;
if (preg_match('/^(\d+)([KMG]?)$/i', $esMemoryLimit, $esMemoryMatch) === 1) {
    $esMemoryBytes = (int)$esMemoryMatch[1] * ['' => 1, 'K' => 1024, 'M' => 1048576, 'G' => 1073741824][strtoupper($esMemoryMatch[2])];
}
if ($esMemoryBytes !== -1 && $esMemoryBytes < 536870912) {
    ini_set('memory_limit', '512M');
}

global $argv;


try {
    try {
        // If we are called via CLI, this typically means we're should run as a daemon.
        // Else we expect some output on the webpage or do debugging.
        $mode = Support::is_cli() ? ES_MODE_SYNC_POLL : ES_MODE_SYNC;

        switch($argv[1]??''){
            case '-s':
                $mode = ES_MODE_SYNC;
                break;
            case '-S':
                $mode = ES_MODE_SYNC_POLL;
                break;
            case '-l':
                // List folder
                $mode = ES_MODE_LIST_ALL_FOLDER;
                break;
            case '-L':
                // List folder and mail
                $mode = ES_MODE_LIST_ALL_FOLDER_ALL_MAIL;
                break;
            default:
                break;
        }

        $emailSync = new EmailSync($mode);
        $emailSync->process();

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

if (!empty($answer[API_MESSAGE])) {
    echo $answer[API_MESSAGE];

    // The watchdog discards stdout/stderr - record the exit cause in the imap log too.
    // Defensive try: the exception may have fired before Store/Path were initialized.
    try {
        $logLevelMin = Logger::nameToLevel(Store::getInstance()->getVar(SYSTEM_IMAP_LOG_MODE, STORE_SYSTEM));
        Logger::logMessage(Logger::linePreTimestamp() . 'email-sync.php exits: ' . $answer[API_MESSAGE],
            Path::absoluteImapLogFile(), FILE_MODE_APPEND, LOG_LEVEL_ERROR, $logLevelMin);
    } catch (\Throwable $ignore) {
        // logging must never mask the original error output
    }
}
