#!@PHP_BIN@
<?php

/*
 * Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * For more information : contact@centreon.com
 *
 */

$debug = 0;

ini_set("display_errors", "Off");

require_once realpath(__DIR__ . "/../config/centreon.config.php");
require_once realpath(__DIR__ . "/../config/bootstrap.php");

define('APPLICATION_PATH', realpath(__DIR__));
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../lib'),
    realpath(APPLICATION_PATH . '/../www/class/centreon-clapi'),
    get_include_path()
)));

define('_CLAPI_LIB_', realpath(__DIR__ . "/../lib"));
define('_CLAPI_CLASS_', realpath(__DIR__ . "/../www/class/centreon-clapi"));

global $version;

/**
 * Declare Options
 */
$shortopts = "";
$shortopts .= "d"; /* Debug mode */
$shortopts .= "u:"; /* Users */
$shortopts .= "p:"; /* Password */
$shortopts .= "s"; /* Sha1 mode */
$shortopts .= "o:"; /* Object type */
$shortopts .= "v:"; /* variables */
$shortopts .= "h"; /* Help */
$shortopts .= "V"; /* Version */
$shortopts .= "a:"; /* Action */
$shortopts .= "i:"; /* Import Massive data */
$shortopts .= "e"; /* Export all configuration */
$shortopts .= "w"; /* Used only for starting centreon worker process */

$longopts = array(
    "select:",
    "filter-type:",
    "filter-ariane:"
);

$options = getopt($shortopts, $longopts);
if (isset($options['d'])) {
    $debug = 1;
}
$useSha1 = false;
if (isset($options['s'])) {
    $useSha1 = true;
}
if ($debug) {
    print_r($options);
} else {
    // Set logging options
    if (defined("E_DEPRECATED")) {
        ini_set("error_reporting", E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
    } else {
        ini_set("error_reporting", E_ALL & ~E_NOTICE & ~E_STRICT);
    }
}

require_once _CENTREON_ETC_ . "/centreon.conf.php";
require_once _CLAPI_CLASS_ . "/centreonAPI.class.php";
require_once _CLAPI_CLASS_ . "/centreonUtils.class.php";

$dbConfig['host'] = hostCentreon;
$dbConfig['username'] = user;
$dbConfig['password'] = password;
$dbConfig['dbname'] = db;
if (defined('port')) {
    $dbConfig['port'] = port;
} elseif ($p = strstr($dbConfig['host'], ':')) {
    $p = substr($p, 1);
    if (is_numeric($p)) {
        $dbConfig['port'] = $p;
    }
}
$db = $dependencyInjector['configuration_db'];
$db->query('SET NAMES utf8');
$dbConfig['dbname'] = $conf_centreon['dbcstg'];
$db_storage = $dependencyInjector['realtime_db'];

/**
 * Create Centreon API object
 */
CentreonClapi\CentreonUtils::setUserName($options['u'] ?? "");
$api = CentreonClapi\CentreonAPI::getInstance(
    ($options["u"] ?? ""),
    ($options["p"] ?? ""),
    ($options["a"] ?? ""),
    $centreon_path,
    $options,
    $dependencyInjector
);
if (isset($options["h"])) {
    $api->printHelp();
}

if (isset($options["V"])) {
    $api->printVersion();
    exit(0);
}

if (isset($options["w"]) && $options['o'] == "CentreonWorker" && !empty($options["u"]) && !empty($options["p"])){
    $api->setLogin($options["u"]);
    $api->setPassword($options["p"]);
    $api->checkUser($useSha1, true);

    try {
        $api->launchAction();
    } catch (\CentreonClapi\CentreonClapiException $e) {
        print $e->getMessage();
        $api->setReturnCode(1);
    } catch (Exception $e) {
        if (isset($debug) && $debug) {
            print $e->getMessage() . "\n";
        }
        print "Please check that your parameters are valid";
        $api->setReturnCode(1);
    }
}

if ($api->login == "" || $api->password == "") {
    if (file_exists($_SERVER["HOME"] . "/.centreonApi")) {
        $uid = posix_getpwuid(fileowner($_SERVER["HOME"] . "/.centreonApi"));
        $perms = substr(sprintf('%o', fileperms($_SERVER["HOME"] . "/.centreonApi")), -3);
        if (strcmp($perms, '400') == 0 && strcmp($_SERVER['USER'], $uid['name']) == 0) {
            $handle = @fopen($_SERVER["HOME"] . "/.centreonApi", "r");
            if ($handle) {
                /**
                 * Read Only the first line
                 */
                $str = fgets($handle);
                fclose($handle);
                $credential = explode(":", $str);
                $api->setLogin($credential[0]);
                $api->setPassword($credential[1]);
                $api->checkUser($useSha1);
            }
            $api->launchAction();
        } else {
            print "Please check access on login file...\n\n";
            $api->printHelp();
        }
    } else {
        $api->printHelp();
    }
} else {

    if (!isset($api->options["V"]) && !isset($api->options["h"])) {
        $api->checkUser($useSha1);
    }

    /*
     * Check action to do
     */
    if (isset($api->options["e"])) {
        $api->export();
    } elseif (isset($api->options["i"])) {
        $api->import($api->options["i"]);
    } elseif (isset($api->options["a"])) {
        try {
            $api->launchAction();
        } catch (\CentreonClapi\CentreonClapiException $e) {
            print $e->getMessage();
            $api->setReturnCode(1);
        } catch (Exception $e) {
            if (isset($debug) && $debug) {
                print $e->getMessage() . "\n";
            }
            print "Please check that your parameters are valid";
            $api->setReturnCode(1);
        }
    } else {
        print "Unknown option";
        $api->setReturnCode(1);
    }
}
$api->close();
