summaryrefslogtreecommitdiff
path: root/lib/nickserver/config.rb
blob: 62623c148fee021f39e9085f62d43b1151b3701d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
require 'yaml'

module Nickserver
  class Config
    PATHS = [
      File.expand_path('../../../config/default.yml', __FILE__),
      '/etc/nickserver.yml'
    ].freeze

    class << self
      attr_accessor :hkp_url
      attr_accessor :hkp_ca_file
      attr_accessor :couch_port
      attr_accessor :couch_host
      attr_accessor :couch_database
      attr_accessor :couch_user
      attr_accessor :couch_password
      attr_accessor :port
      attr_accessor :pid_file
      attr_accessor :user
      attr_accessor :log_file
      attr_accessor :domain
      attr_accessor :domains

      attr_accessor :loaded
      attr_accessor :verbose
    end

    def self.load
      self.loaded ||= begin
        PATHS.each do |file_path|
          load_config(file_path)
        end
        true
      end
      validate
    end

    def self.couch_url
      ['http://',
       couch_auth,
       couch_host,
       ':',
       couch_port,
       '/',
       couch_database].join
    end

    def self.couch_auth
      "#{couch_user}:#{couch_password}@" if couch_user
    end

    private

    def self.validate
      if @hkp_ca_file
        # look for the hkp_ca_file either by absolute path or relative to nickserver gem root
        [@hkp_ca_file, File.expand_path(@hkp_ca_file, "#{__FILE__}/../../../")].each do |file|
          if File.exist?(file)
            @hkp_ca_file = file
            break
          end
        end
        unless File.exist?(@hkp_ca_file)
          STDERR.puts "ERROR in configuration: cannot find hkp_ca_file `#{@hkp_ca_file}`"
          exit(1)
        end
      end
    end

    def self.load_config(file_path)
      YAML.safe_load(File.read(file_path)).each do |key, value|
        begin
          send("#{key}=", value)
        rescue NoMethodError
          STDERR.puts "ERROR in file #{file_path}, '#{key}' is not a valid option"
          exit(1)
        end
      end
      puts "Loaded #{file_path}" if Config.verbose
    rescue Errno::ENOENT => exc
      puts "Skipping #{file_path}" if Config.verbose
    rescue Exception => exc
      STDERR.puts exc.inspect
      exit(1)
    end
  end
end