<?php

// old versions of php < 5.3.0 doesn't have E_DEPRECATED
if (defined('E_DEPRECATED')) {
    error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
} else {
    error_reporting(E_ALL & ~E_NOTICE);
}

date_default_timezone_set('UTC');

// This is to resolve know bug in php built in server
// https://bugs.php.net/bug.php?id=66606
if (!isset($_SERVER['CONTENT_TYPE']) && isset($_SERVER['HTTP_CONTENT_TYPE'])) {
    $_SERVER['CONTENT_TYPE'] = $_SERVER['HTTP_CONTENT_TYPE'];
}

require_once 'config/config.php';
require_once 'vendor/autoload.php';
require_once 'lib/ValidatesRequests.php';
require_once 'lib/CfPdoInterface.php';
require_once 'lib/oauth/OauthException.php';
require_once 'lib/oauth/OauthCfPdo.php';

//load exceptions
require_once 'exceptions/SocketExceptions.php';

require_once 'lib/VcsSettingsLib.php';
require_once 'lib/Tonic.php';
require_once 'lib/ProtectedResource.php';
require_once 'lib/Utils.php';
require_once 'lib/DefaultParameters.php';
require_once 'lib/VcsApi.php';
require_once 'lib/SettingsHelper.php';
require_once 'lib/HostsCleanupSettings.php';
require_once 'lib/CfPdo.php';
require_once 'lib/CfdbPdo.php';
require_once 'lib/UsersList.php';
require_once 'lib/CFHostCount.php';
require_once 'lib/UsersListRequestStructure.php';
require_once 'lib/CfUsers.php';
require_once 'lib/CfRole.php';
require_once 'lib/CfRBAC.php';
require_once 'lib/CfEvent.php';
require_once 'lib/CfTasks.php';
require_once 'lib/FileSystemReader.php';
require_once 'lib/CfHub.php';
require_once 'lib/health_diagnostics/autoload.php';
require_once 'lib/CfFileChanges.php';
require_once 'lib/CFHostByClass.php';
require_once 'lib/CfActions.php';
require_once 'lib/CfInventoryAliases.php';
require_once 'lib/CfDeletedHost.php';
require_once 'lib/CfSshKeys.php';
require_once 'lib/CfCache.php';
require_once 'lib/CfFailedAttempts.php';
require_once 'lib/CfPasswordReset.php';
require_once 'lib/CfMailSettings.php';
require_once 'lib/CfMail.php';
require_once 'lib/CfSetup.php';
require_once 'lib/CfLLMConfig.php';
require_once 'lib/CfAutocomplete.php';
require_once 'lib/HostsCleanupSettings.php';
require_once 'lib/CfHostsCleanup.php';
// load resources
require_once 'resource-v1/Host.php';
require_once 'resource-v1/2FA.php';
require_once 'resource-v1/Query.php';
require_once 'resource-v1/Settings.php';
require_once 'resource-v1/Status.php';
require_once 'resource-v1/Role.php';
require_once 'resource-v1/User.php';
require_once 'resource-v1/Vcs.php';
require_once 'resource-v1/Oauth.php';
require_once 'resource-v1/Changes.php';
require_once 'resource-v1/Event.php';
require_once 'resource-v1/InternalTasks.php';
require_once 'resource-v1/PolicyBrowser.php';
require_once 'resource-v1/HealthDiagnostic.php';
require_once 'resource-v1/RBAC.php';
require_once 'resource-v1/FileChanges.php';
require_once 'resource-v1/Actions.php';
require_once 'resource-v1/SshKey.php';
require_once 'resource-v1/ResetPassword.php';
require_once 'resource-v1/Setup.php';
require_once 'resource-v1/AISettings.php';
require_once 'resource-v1/Autocomplete.php';
require_once 'resource-v1/HostCleanup.php';
// load modules
require_once 'modules/inventory/autoload.php';
require_once 'modules/federated-reporting/autoload.php';
require_once 'modules/cmdb/autoload.php';
require_once 'modules/events/autoload.php';
require_once 'modules/build/autoload.php';
require_once 'modules/hostGroups/autoload.php';
require_once 'modules/auditLog/autoload.php';
require_once 'modules/aiChat/autoload.php';
require_once 'modules/containers/autoload.php';
//load services
require_once 'services/RbacAccessService.php';
//load helpers
require_once 'helpers/YamlHelper.php';
require_once 'helpers/StringHelper.php';
require_once 'helpers/RbacHelper.php';
require_once 'helpers/Validator.php';
require_once 'helpers/TwoFaHelper.php';
require_once 'helpers/NetworkHelper.php';
require_once 'helpers/DatabaseHelper.php';

//load validators
require_once 'validators/autoloader.php';


//load middlewares
require_once 'middlewares/autoload.php';

require_once 'templates/TemplateLoader.php';

define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));
// Path to the front controller (this file)
define('FCPATH', str_replace(SELF, '', __FILE__));

define('TEMPLATES_PATH', FCPATH . '/templates');

$vcsConfigFilePath = Utils::getVcsConfigFilePath();
define('VCSCONFIGPATH', $vcsConfigFilePath);

$request = new Request(array(
    'baseUri' => '/api',
    'mimetypes' => array(
        'json-v1' => 'application/vnd.cfengine.enterprise-v1+json'
    )
));

try {
    $format = DefaultParameters::format();
    if (!empty($request->accept)) {
        $format = $request->mostAcceptable(array(
            DefaultParameters::format()
        ));
    }


    switch ($format) {
        case 'json-v1':

            break;

        default:
            throw new ResponseException("Unsupported format or version requested", Response::NOTACCEPTABLE);
    }

    DefaultParameters::check();

    \middlewares\SetupGuard::handle($request);
    \middlewares\RbacGuard::handle($request);
    $resource = $request->loadResource();
    $response = $resource->exec($request);
} catch (OauthException $e) {

    $response = new Response($request);
    $response->body = $e->getOauthBody();
    $response->code = $e->getOauthCode();

    foreach ($e->getOauthHttpHeaders() as $key => $value) {
        $response->addHeader($key, $value);
    }

} catch (ResponseException $e) {

    switch ($e->getCode()) {
        case Response::UNAUTHORIZED:
            $response = $e->response($request);

            break;

        case Response::INTERNALSERVERERROR:
            $response = $e->response($request);

            break;

        default:
            $response = $e->response($request);
    }
} catch (CFAPIException $e) {
    $response = new Response($request);
    $response->body = Utils::CFAPIErrorMessageByCode($e->getCode(), $e->getMessage());
    $response->code = Utils::CFAPIErrorCodeToHttpCode($e->getCode());
} catch (InvalidArgumentException $e) {
    $response = new Response($request);
    $response->body = $e->getMessage();
    $response->code = Response::UNPROCESSABLE_ENTITY;
} catch (AccessDenyException $e) {
    $response = new Response($request);
    $response->body = $e->getMessage();
    $response->code = Response::FORBIDDEN;
} catch (Exception $e) {
    $response = new Response($request);
    $response->body = $e->getMessage();
    $response->code = Response::INTERNALSERVERERROR;
}

// Add newline to API error responses
if ($response->code >= 400) {
    $response->body = $response->body . PHP_EOL;
}

$response->addHeader('Content-type', 'application/vnd.cfengine.enterprise-v1+json');
$response->output();
return;
