#!@PHP_BIN@
<?php
/*
 * Copyright 2005-2020 Centreon
 * Centreon is developed by : Julien Mathis and Romain Le Merlus under
 * GPL Licence 2.0.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation ; either version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, see <http://www.gnu.org/licenses>.
 *
 * Linking this program statically or dynamically with other modules is making a
 * combined work based on this program. Thus, the terms and conditions of the GNU
 * General Public License cover the whole combination.
 *
 * As a special exception, the copyright holders of this program give Centreon
 * permission to link this program with independent modules to produce an executable,
 * regardless of the license terms of these independent modules, and to copy and
 * distribute the resulting executable under terms of Centreon choice, provided that
 * Centreon also meet, for each linked independent module, the terms  and conditions
 * of the license of that module. An independent module is a module which is not
 * derived from this program. If you modify this program, you may extend this
 * exception to your version of the program, but you are not obliged to do so. If you
 * do not wish to do so, delete this exception statement from your version.
 *
 * 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();
