BSD and expact license modified
[KiwiIRC.git] / server / configuration.js
1 var fs = require('fs'),
2 events = require('events'),
3 util = require('util'),
4 path = require('path'),
5 winston = require('winston');
6
7 var config_filename = 'config.js',
8 config_dirs = ['/etc/kiwiirc/', __dirname + '/../'],
9 environment = 'production',
10 loaded_config = Object.create(null);
11
12 var Config = function () {
13 events.EventEmitter.call(this);
14 };
15 util.inherits(Config, events.EventEmitter);
16
17 Config.prototype.loadConfig = function (manual_config_file) {
18 var new_config,
19 conf_filepath,
20 i;
21
22 if ((manual_config_file) || (this.manual_config_file)) {
23 manual_config_file = path.resolve(path.normalize(manual_config_file || this.manual_config_file));
24 if (fs.existsSync(manual_config_file)) {
25 try {
26 if (fs.lstatSync(manual_config_file).isFile() === true) {
27 // Clear the loaded config cache
28 delete require.cache[require.resolve(manual_config_file)];
29
30 // Try load the new config file
31 new_config = require(manual_config_file);
32
33 // Save location of configuration file so that we can re-load it later
34 this.manual_config_file = manual_config_file;
35 }
36 } catch (e) {
37 winston.error('An error occured parsing the config file %s: %s', manual_config_file, e.message);
38 process.exit(1);
39 }
40 } else {
41 winston.error('Could not find config file %s', manual_config_file);
42 process.exit(1);
43 }
44 } else {
45 // Loop through the possible config paths and find a usable one
46 for (i = 0; i < config_dirs.length; i++) {
47 conf_filepath = config_dirs[i] + config_filename;
48
49 try {
50 if (fs.lstatSync(conf_filepath).isFile() === true) {
51 // Clear the loaded config cache
52 delete require.cache[require.resolve(conf_filepath)];
53
54 // Try load the new config file
55 new_config = require(conf_filepath);
56 break;
57 }
58 } catch (e) {
59 switch (e.code) {
60 case 'ENOENT': // No file/dir
61 break;
62 default:
63 winston.warn('An error occured parsing the config file %s%s: %s', config_dirs[i], config_filename, e.message);
64 return false;
65 }
66 continue;
67 }
68 }
69 }
70
71 if (new_config) {
72 loaded_config = new_config;
73 global.config = new_config[environment] || {};
74 this.emit('loaded');
75 return loaded_config;
76 } else {
77 return false;
78 }
79 };
80
81
82
83 Config.prototype.setEnvironment = function (new_environment) {
84 environment = new_environment;
85 };
86
87 // Get the current config. Optionally for a different environment than currently set
88 Config.prototype.get = function (specific_environment) {
89 specific_environment = specific_environment || environment;
90
91 return loaded_config[specific_environment] || {};
92 };
93
94 module.exports = new Config();