<?php
/**
 * Class that takes care of configuration
 *
 * This file is part of Zoph.
 *
 * Zoph 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, or
 * (at your option) any later version.
 *
 * Zoph 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 Zoph; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @author Jeroen Roos
 * @package Zoph
 */

require_once("db/db.inc.php");
use db\db;

/**
 * This class takes care of loading and processing settings
 *
 * @author Jeroen Roos
 * @package Zoph
 */
class settings {

    public static $php_loc;
    public static $instance;
    /**
     * Load ini file, as defined in the INI_FILE constant
     * Check if these settings are still made in config.inc.php
     * and figure out which of the settings should be used.
     */
    public static function loadINI($instance="") {
        if (!defined("INI_FILE")) {
            define("INI_FILE", "/etc/zoph.ini");
        }
        if (file_exists(INI_FILE)) {
            $ini=parse_ini_file(INI_FILE, true);

            if ($ini === false) {
                throw new zophININotReadableException ("Could not read " . INI_FILE . ". Check permissions.");
            }
            if (!empty($instance)) {
                if (!isset($ini[$instance])) {
                    throw new zophINIInstanceNotFoundException("Instance " . $instance .
                        " not found in " . INI_FILE);
                }
            } else {
                // No instance given, autodetect
                $instance=static::detectInstance($ini);
            }
            return $ini[$instance];
        } else {
            throw new zophININotFoundException (INI_FILE . " not found.");
        }
    }



    /**
     * Detect which Zoph instance is used from php path
     * @param array ini file as parsed by php function parse_ini_file()
     */

    public static function detectInstance(array $ini) {
        $php_loc=dirname($_SERVER['SCRIPT_FILENAME']);
        if (substr($php_loc, -8) == "/service") {
            $php_loc = substr($php_loc, 0, -8);
        } else if (substr($php_loc, -3) == "/js") {
            $php_loc = substr($php_loc, 0, -3);
        }

        foreach ($ini as $instance=>$i) {
            if (!isset($i["php_location"])) {
                log::msg("php_location setting missing from " . $instance . " in " .
                    INI_FILE, log::FATAL, log::GENERAL);
            } else if ($php_loc==$i["php_location"]) {
                static::$instance=$instance;
                return $instance;
            }
        }
        // No corresponding settings found.
        throw new zophINIInstanceNotFoundException("No php_location setting in " . INI_FILE . " found that matches " . $php_loc);
    }

    /**
     * Parse values from ini file.
     * @param array section from ini file
     * @todo get rid of constants.
     */
    public static function parseINI($i) {
        if (!isset($i["php_location"])) {
            $php_loc=dirname($_SERVER['SCRIPT_FILENAME']);
            throw new zophINIInstanceNotFoundException("No php_location setting in " . INI_FILE . " found that matches " . $php_loc);
        } else if (!defined("TEST")) {
            static::$php_loc=$i["php_location"];
        } else {
            settings::$php_loc=getcwd() . DIRECTORY_SEPARATOR . "php";
        }

        $required = array("db_host", "db_name", "db_user", "db_pass", "db_prefix");
        foreach ($required as $setting) {
            if (!isset($i[$setting])) {
                throw new zophINIMissingSettingException($setting . " setting missing from " .  INI_FILE);
            }
        }
        db::setLoginDetails(
            $i["db_host"],
            $i["db_name"],
            $i["db_user"],
            $i["db_pass"],
            $i["db_prefix"]
        );
        return true;
    }
}

if (!defined("CLI")) {
    if (defined("TEST")) {
        /* unittest code cannot use autodetection of PHP location
           because the code is executed from PHPUnit context */
        $i=settings::loadINI(INSTANCE);
        set_include_path(get_include_path() . PATH_SEPARATOR . getcwd() . DIRECTORY_SEPARATOR . "php");
    } else {
        $i=settings::loadINI();
    }
    settings::parseINI($i);
}
