require 'singleton' require 'json' module Adminix class Config include Singleton DEFAULT_HOST = 'http://api.adminix.io'.freeze attr_accessor( :service_name, :service_id, :service_address, :host, :secret_key, :monitor_logs_paths, :options, :commands ) def self.setup(opts) conf = self.instance conf.service_id = opts[:service_id] || ENV['ADMINIX_SERVICE_ID'] conf.service_name = opts[:service_name] conf.secret_key = opts[:secret_key] || ENV['ADMINIX_SECRET_KEY'] conf.export end def attributes { service_name: service_name, service_id: service_id, service_address: service_address, secret_key: secret_key, options: options || [], commands: commands || [] } end def file_exists? File.exists?("#{ENV['HOME']}/.adminix.json") end def export(path=nil) file_path = path || "#{ENV['HOME']}/.adminix.json" file_content = JSON.pretty_generate(attributes) File.delete(file_path) if File.exists?(file_path) File.open(file_path, 'w') { |file| file.write(file_content) } end def import content = File.read(config_file_path) hs = JSON.parse(content) self.service_name = hs['service_name'] self.service_id = hs['service_id'] || ENV['ADMINIX_SERVICE_ID'] self.service_address = hs['service_address'] self.secret_key = hs['secret_key'] || ENV['ADMINIX_SECRET_KEY'] self.host = hs['host'] || ENV['ADMINIX_CONFIG_HOST'] || DEFAULT_HOST self.options = hs['options'] || [] self.commands = hs['commands'] || [] valid? end def config_file_path return @config_path unless @config_path.nil? paths = [ "#{ENV['HOME']}/.adminix.json", '.adminix.json' ] paths << ENV['ADMINIX_CONFIG_PATH'] if !ENV['ADMINIX_CONFIG_PATH'].nil? config_path = nil paths.reverse.each do |path| if File.exists?(path) @config_path = path break end end @config_path or raise "adminix.json doesn't exists" end def valid? errors = {} if service_name.nil? errors[:service_name] ||= [] errors[:service_name] << "should't be blank" end if service_id.nil? errors[:service_id] ||= [] errors[:service_id] << "should't be blank" end if secret_key.nil? errors[:secret_key] ||= [] errors[:secret_key] << "should't be blank" end unless monitor_logs_paths.nil? unless monitor_logs_paths.is_a? Array errors[:monitor_logs_paths] << "should be array" end end unless options.nil? unless options.is_a? Array errors[:options] << "should be array" end end unless commands.nil? unless commands.is_a? Array errors[:commands] << "should be array" end end @errors = errors errors.count == 0 end def errors @errors end end end