#!/usr/bin/env php
<?php
if (!defined('STDIN')) {
    define('STDIN', fopen('php://stdin', 'r'));
}
define('LARAVEL_START', microtime(true));

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/

$domainName = getDomainName();
$mainHome = getMainHome();

$domainAppPath = __DIR__;
if (is_dir($mainHome . '/rvsitebuildercms')) {
    if (is_dir($mainHome . '/rvsitebuildercms/' . $domainName)) {
        $domainAppPath = $mainHome . '/rvsitebuildercms/' . $domainName;
    } else {
        if (is_dir($mainHome . '/rvsitebuildercms/localhost')) {
            $domainAppPath = $mainHome . '/rvsitebuildercms/localhost';
        }
    }
}

if (file_exists($domainAppPath . '/vendor/autoload.php')) {
    require $domainAppPath . '/vendor/autoload.php';
    $packagesPath = $domainAppPath . '/packages';
    $vendor_names = scandir($packagesPath);
    foreach ($vendor_names as $vendor_name) {
        if (preg_match("/^\./", $vendor_name)) {
            continue;
        }
        $package_names = scandir($packagesPath . '/' . $vendor_name);
        foreach ($package_names as $package_name) {
            if (preg_match("/^\./", $package_name)) {
                continue;
            }
            $auto_load_file = $packagesPath . '/' . $vendor_name . '/' . $package_name . '/vendor/autoload.php';
            if (is_file($auto_load_file)) {
                require $auto_load_file;
            }
        }
    }
} else {

    $composerPath = $domainAppPath . '/composer.json';
    if (is_file($composerPath)) {
        $data = file_get_contents($composerPath);
    }
    $requiresPhp = json_decode($data ?? '', true)['require']['php'] ?? '7.3-7.4';

    echo '<h2>Not found RVSiteBuilder CMS App in ' . get_include_path() . '<h2>';
    echo '<pre>
Please contact your provider with info:
1. RVSitebuilder CMS App have not install.
2. Not found vendor path.
3. Your PHP version ' . PHP_VERSION . ' not compatible, Our system require PHP ' . $requiresPhp . '

' . getKbDomainWww() . '
</pre>';
    exit;
}


$app = require_once $domainAppPath . '/bootstrap/app.php';

/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/

$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);

$status = $kernel->handle(
    $input = new Symfony\Component\Console\Input\ArgvInput,
    new Symfony\Component\Console\Output\ConsoleOutput
);

/*
|--------------------------------------------------------------------------
| Shutdown The Application
|--------------------------------------------------------------------------
|
| Once Artisan has finished running, we will fire off the shutdown events
| so that any final work may be done by the application before we shut
| down the process. This is the last thing to happen to the request.
|
*/

$kernel->terminate($input, $status);

exit($status);


// cms custom function
function file_exists_include_path($include_file)
{
    $included_path_lists = explode(':', get_include_path());
    $found = 0;
    foreach ($included_path_lists as $include_path) {
        if (file_exists($include_path . '/' . $include_file)) {
            $found = 1;
            break;
        }
    }
    return $found;
}

function getMainHome()
{

    $user_path = '';
    $document_root = $_SERVER['DOCUMENT_ROOT'];
    $user_paths = [];
    $open_basedir_paths = get_open_basedir_paths();

    if (php_sapi_name() === 'cli') {
        if (posix_getuid() != 0) {
            $document_root = dirname(__FILE__);
        } else {
            return $user_path;
        }
    } else {
        $document_root = $_SERVER['DOCUMENT_ROOT'];
    }

    // case devmmode
    if (file_exists($document_root . '/../storage/devmode')) {
        return dirname($document_root . '../');
    }


    # CASE open_basedir
    if (\count($open_basedir_paths)) {
        $user_paths = $open_basedir_paths;
    } else {
        if (isset($_SERVER['HOME'])) {
            if (!\in_array($_SERVER['HOME'], $user_paths)) {
                array_push($user_paths, $_SERVER['HOME']);
            }
        }
        $posix_user_path = '';
        if (\function_exists('posix_getuid')) {
            $webuid = posix_getuid();
            $userinfo = posix_getpwuid($webuid);
            if (is_dir($userinfo['dir'])) {
                if (!\in_array($userinfo['dir'], $user_paths)) {
                    array_push($user_paths, $userinfo['dir']);
                }
            }
        }
        // case  have posix_getpwuid get uid by owner dir
        if (\function_exists('posix_getpwuid')) {
            $stat = stat($document_root);
            if (isset($stat['uid'])) {
                $userinfo = posix_getpwuid($stat['uid']);
                if (is_dir($userinfo['dir'])) {
                    if (!\in_array($userinfo['dir'], $user_paths)) {
                        array_push($user_paths, $userinfo['dir']);
                    }
                }
            }
            if (isset($stat['gid'])) {
                $userinfo = posix_getpwuid($stat['gid']);
                if (is_dir($userinfo['dir'])) {
                    if (!\in_array($userinfo['dir'], $user_paths)) {
                        array_push($user_paths, $userinfo['dir']);
                    }
                }
            }
        }
        // case  find home path from document_root ( /home/amarin/public_html => /home/amarin )
        if ($posix_user_path == '') {
            $paths = preg_split("/\//", $document_root);
            $loop_dim = \count($paths);
            for ($i = 0; $i < $loop_dim; ++$i) {
                $test_path = implode('/', $paths);
                if (is_dir($test_path)) {
                    if (!\in_array($test_path, $user_paths)) {
                        array_push($user_paths, $test_path);
                    }
                }
                array_pop($paths);
            }
        }
    }

    //find for  /home/arnut ,  /var/www
    $homepath = preg_grep("/^\/home\/\w+$/", $user_paths);
    if (count($homepath) > 0) {
        return array_values($homepath)[0];
    }
    $varwww  = preg_grep("/(^\/var\/www)/", $user_paths);
    if (count($varwww) > 0) {
        return array_values($varwww)[0];
    }

    //find path for app cms
    foreach ($user_paths as $user_path_var) {
        if (is_file($user_path_var)) {
            continue;
        }
        if ($user_path_var == $document_root) {
            continue;
        }
        if (preg_match("/(^\/tmp)|(\/tmp$)/", $user_path_var)) {
            continue;
        }
        // TODO find path for cPanel, VPS, Pleak , ISPconfig and etc.
        if (is_writable($user_path_var)) {
            $user_path = $user_path_var;
            break;
        }
    }

    // other ../
    if (php_sapi_name() === 'cli') {
        $user_path = realpath($document_root . '/../../');
    } else {
        $user_path = realpath($document_root . '/../');
    }

    return $user_path;
}

function get_open_basedir_paths()
{
    $open_basedir_paths = [];
    if (function_exists('ini_get')) {
        $open_basedir_str =  trim(ini_get('open_basedir'));
        if ($open_basedir_str != '') {
            $open_basedir_paths = explode(":", strtolower($open_basedir_str));
        }
    }
    return $open_basedir_paths;
}

function getDomainName()
{
    $domainName = '';
    if (php_sapi_name() === 'cli') {
        if (posix_getuid() != 0) {
            $paths = preg_split("/\//", __DIR__);
            $domainName = array_pop($paths);
        }
    } else {
        $parts = parse_url($_SERVER['HTTP_HOST']);
        $domainName = $parts['path'];
    }
    return $domainName;
}


//is www.domain.com
function getKbDomainWww()
{
    $domainName = getDomainName();

    $isWwwDomain = '';
    if (preg_match("/^www\./i", $domainName)) {
        $isWwwDomain =  '<u>Please contact website admin to fix by <a target="_blank" href="https://support.rvglobalsoft.com/hc/en-us/articles/360035144693-Website-error-Not-found-RVSiteBuilder-CMS-App-in-opt-alt-php73-usr-share-pear">solution.</a></u>';
    }
    return $isWwwDomain;
}
