<?php









define('DS', DIRECTORY_SEPARATOR);
$root = dirname(__DIR__);

if (PHP_SAPI !== 'cli') {
    exit(1);
}

ignore_user_abort(true);
ini_set('display_errors', '0');
ini_set('log_errors', '1');

$error_log = isset($argv[3]) ? (string)$argv[3] : '';
if (
    $error_log !== ''
    && strpos($error_log, "\0") === false
    && preg_match('/^max-qr-worker-\d+-[a-f0-9]{24}\.err\.log$/', basename($error_log))
) {
    $error_dir = dirname($error_log);
    if (is_dir($error_dir) && is_writable($error_dir)) {
        ini_set('error_log', $error_log);
    }
}

$easychat_max_qr_worker_finished = false;
function easychat_max_qr_worker_fail(string $code, int $exit_code = 1): void {
    global $easychat_max_qr_worker_finished;
    $safe_code = preg_match('/^[a-z0-9_]{1,80}$/', $code) ? $code : 'worker_failed';
    $easychat_max_qr_worker_finished = true;
    error_log('EASYCHAT_MAX_QR_ERROR=' . $safe_code);
    exit($exit_code);
}
register_shutdown_function(static function (): void {
    global $easychat_max_qr_worker_finished;
    if (!$easychat_max_qr_worker_finished) {
         
         
        error_log('EASYCHAT_MAX_QR_ERROR=worker_terminated_unexpectedly');
    }
});

if (!is_file($root . DS . 'config.php')) {
    easychat_max_qr_worker_fail('config_missing');
}

require_once $root . DS . 'core' . DS . 'runtime_reader_lock.php';
$easychat_runtime_reader_lock = easychat_runtime_reader_lock_acquire($root, false);

require_once $root . DS . 'library' . DS . 'request_context.php';
\EasyChat\Library\RequestContext::bootstrapServerDefaults([
    'HTTP_HOST' => 'localhost',
    'SCRIPT_NAME' => '/cli/max_qr_auth_worker.php',
    'HTTPS' => 'off',
    'HTTP_X_FORWARDED_PROTO' => '',
    'HTTP_X_FORWARDED_SSL' => '',
    'SERVER_PORT' => 80,
]);

require_once $root . DS . 'config.php';
require_once SITE_PATH . DS . 'core' . DS . 'autoload.php';

$channel_id = isset($argv[1]) ? (int)$argv[1] : 0;
$attempt_id = isset($argv[2]) ? (string)$argv[2] : '';
if ($channel_id <= 0 || !preg_match('/^[a-f0-9]{24}$/', $attempt_id)) {
    easychat_max_qr_worker_fail('invalid_arguments');
}

try {
    $registry = new Registry();
    $db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE, DB_PORT);
    $registry->set('db', $db);
    (new EasyChat\Library\AppClock($registry))->syncDatabaseSessionTimezone();

    $service = new EasyChat\Library\Messenger\MaxAuthService($registry);
    $result = $service->runQrWorker($channel_id, $attempt_id);
    if (!empty($result['success'])) {
        $easychat_max_qr_worker_finished = true;
        exit(0);
    }
    easychat_max_qr_worker_fail((string)($result['error'] ?? 'worker_failed'));
} catch (Throwable $e) {
     
     
    $technical = strtolower(get_class($e) . ' ' . $e->getMessage());
    $code = 'bootstrap_failed';
    if (strpos($technical, 'mysqli') !== false || strpos($technical, 'pdo_mysql') !== false || strpos($technical, 'database driver') !== false) {
        $code = 'database_driver_missing';
    } elseif (strpos($technical, 'permission denied') !== false || strpos($technical, 'not writable') !== false || strpos($technical, 'storage') !== false) {
        $code = 'storage_unavailable';
    }
    easychat_max_qr_worker_fail($code);
}
