#--
# CyborgHood, a distributed system management software.
# Copyright (c) 2009-2010 Marc Dequènes (Duck) <Duck@DuckCorp.org>
#
# 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 3 of the License, or
# (at your option) any later version.
#
# 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/>.
#++

require 'singleton'
require 'yaml'
require 'cyborghood/base/config_setup'

module CyborgHood
  class Config
    include Singleton

    CONFFILE_GLOBAL = "cyborghood.conf"
    CONFFILE_BOT = "cyborghood_%s.conf"

    def self.load(name = nil)
      # load all config parts
      config = fetch_config
      unless name.nil?
        config_spc = fetch_config(name)
        config = merge_configs(config, config_spc) if config_spc
      end

      # create config object for easier access
      @@config = config.to_ostruct.freeze
    end

    def method_missing(sym, *args, &block)
      begin
        @@config.send sym, *args, &block
      rescue
        nil
      end
    end

    private

    def self.fetch_config(name = nil)
      begin
        if name.nil?
          filename = CONFFILE_GLOBAL
        else
          filename = sprintf(CONFFILE_BOT, name)
        end
        filepath = File.join(File.expand_path(CFG_DIR), filename)
        str = File.read(filepath)
        YAML.load(str)
      rescue
        logger.fatal "Problems fetching configuration file '" + filepath + "': " + $!
        exit 1
      end
    end

    def self.merge_configs(conf1, conf2)
      new_conf = conf1.dup
      conf2.each_pair do |k, v|
        if conf1.has_key?(k) and conf1[k].is_a?(Hash) and v.is_a?(Hash)
          new_conf[k] = merge_configs(conf1[k], v)
        else
          new_conf[k] = v
        end
      end
      return new_conf
    end
  end
end
