#! /usr/bin/php
<?php
/**
 * Copyright 2005-2015 CENTREON
 * Centreon is developped 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(dirname(__FILE__).'/../config/centreon.config.php');

define('APPLICATION_PATH', realpath(dirname(__FILE__)));
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(dirname(__FILE__))."/../lib");
define('_CLAPI_CLASS_', realpath(dirname(__FILE__))."/../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 */

$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";
require_once _CLAPI_LIB_."/Centreon/Db/Manager/Manager.php";

$dbConfig['host'] = $conf_centreon['hostCentreon'];
$dbConfig['username'] = $conf_centreon['user'];
$dbConfig['password'] = $conf_centreon['password'];
$dbConfig['dbname'] = $conf_centreon['db'];
if (isset($conf_centreon['port'])) {
    $dbConfig['port'] = $conf_centreon['port']; 
} elseif ($p = strstr($dbConfig['host'], ':')) {
    $p = substr($p, 1);
    if (is_numeric($p)) {
        $dbConfig['port'] = $p;
    }
}
$db = Centreon_Db_Manager::factory('centreon', 'pdo_mysql', $dbConfig);
$db->query('SET NAMES utf8');
$dbConfig['dbname'] = $conf_centreon['dbcstg'];
$db_storage = Centreon_Db_Manager::factory('storage', 'pdo_mysql', $dbConfig);
try {
  $db->getConnection();
  $db_storage->getConnection();
} catch (Exception $e) {
    echo sprintf("Could not connect to database. Check your configuration file %s\n", _CENTREON_ETC_.'/centreon.conf.php');
    if (isset($options['h'])) {
        CentreonClapi\CentreonAPI::printHelp(false, 1);
    }
    exit(1);
  }

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

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

/**
 * Now works
 */
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();
    } else if (isset($api->options["i"])) {
        $api->import($api->options["i"]);
    } else if (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();
