require "socket"

class DevopsConfig

  OBJECT_NAME = /([\w\-]+)/

  @@config = nil

  class << self
    def read config_file=nil
      if config_file.nil?
        config_file = ENV['DEVOPS_CONFIG'] || ENV['CONFIG'] || File.join(File.dirname(__FILE__), '../config.rb')
      end
      config = {
        :url_prefix => "",
        :devops_dir => File.join(ENV["HOME"], ".devops")
      }
      if File.exists? config_file
        eval File.read config_file
      else
        raise "No config file '#{config_file}' found"
      end
      addr = first_public_ipv4 || first_private_ipv4
      config[:address] = if addr.nil?
        "localhost"
      else
        addr.ip_address
      end

      config[:report_dir_v2] = File.expand_path(File.join(config[:devops_dir], "report", "v2"))
      config[:project_info_dir] = File.expand_path(File.join(config[:devops_dir], "project_info", "v2"))

      DevopsConfig.config = config
    end

    def config= config
      @@config = config
    end

    def config
      @@config
    end

    def [](key)
      @@config[key]
    end

    def first_private_ipv4
      Socket.ip_address_list.detect{|intf| intf.ipv4_private?}
    end

    def first_public_ipv4
      Socket.ip_address_list.detect{|intf| intf.ipv4? and !intf.ipv4_loopback? and !intf.ipv4_multicast? and !intf.ipv4_private?}
    end

  end

end
