<?php

declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| Direct web access is not allowed
|--------------------------------------------------------------------------
*/

$scriptFilename =
    isset($_SERVER['SCRIPT_FILENAME'])
        ? realpath((string)$_SERVER['SCRIPT_FILENAME'])
        : false;

if (
    $scriptFilename !== false &&
    hash_equals(
        __FILE__,
        $scriptFilename
    )
) {
    http_response_code(404);
    exit;
}

/*
|--------------------------------------------------------------------------
| Discover the private Atlas client
|--------------------------------------------------------------------------
|
| No cPanel username, customer domain or absolute account path is embedded here.
| Walk upward until the account-level .atlas-client installation is found.
|--------------------------------------------------------------------------
*/

$start =
    realpath(__DIR__);

if ($start === false) {
    throw new RuntimeException(
        'Atlas integration root is unavailable.'
    );
}

$bridgeOwner =
    fileowner(__FILE__);

if ($bridgeOwner === false) {
    throw new RuntimeException(
        'Atlas integration owner is unavailable.'
    );
}

$current =
    $start;

$bootstrap =
    null;

for ($depth = 0; $depth < 8; $depth++) {

    $candidate =
        $current .
        '/.atlas-client/app/src/Service/' .
        'ClientIntegrationBootstrap.php';

    if (
        is_file($candidate) &&
        !is_link($candidate)
    ) {
        $real =
            realpath($candidate);

        if (
            $real !== false &&
            hash_equals(
                $candidate,
                $real
            )
        ) {
            $owner =
                fileowner($real);

            if (
                $owner !== false &&
                $owner === $bridgeOwner
            ) {
                $bootstrap =
                    $real;

                break;
            }
        }
    }

    $parent =
        dirname($current);

    if ($parent === $current) {
        break;
    }

    $current =
        $parent;
}

if ($bootstrap === null) {
    throw new RuntimeException(
        'Atlas client integration bootstrap is unavailable.'
    );
}

require_once
    $bootstrap;

if (
    !class_exists(
        \Atlas\Client\Service\ClientIntegrationBootstrap::class,
        false
    )
) {
    throw new RuntimeException(
        'Atlas client integration bootstrap failed to load.'
    );
}
