/**
 * This refers to the Dougal instance configuration, taken
 * from $DOUGAL_ROOT/etc/config.yaml
 */

const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const YAML = require('yaml');

const cfgPrefix = process.env.DOUGAL_ROOT || ((process.env.HOME || ".") + "/software");
const cfgPath = process.env.DOUGAL_API_CONFIG || (cfgPrefix+"/etc/www/config.json");
const globalCfgPath = cfgPrefix+"/etc/config.yaml";
const usersCfgPath = cfgPrefix+"/etc/users.yaml";

let config = {}

try {
	if (!fs.existsSync(cfgPath)) {

		if (process.env.NODE_ENV == "production") {
			console.error("Configuration file not found", path.resolve(cfgPath));
			process.exit(-1);
		} else {

			console.warn("Configuration file not found", path.resolve(cfgPath));
			const buffer = Buffer.alloc(64);
			crypto.randomFillSync(buffer, 0, buffer.length);
			const secret = buffer.toString("base64");

			config = {
				"jwt": {
					secret,
					options: {
						expiresIn: 15*60*1000
					}
				},
				"db": {
					"user": "postgres",
					"host": "localhost",
					"database": "dougal",
					"port": 5432,
					"connection_string": "host=localhost port=5432 dbname=dougal user=postgres"
				}
			}
			console.warn("Autogenerated configuration file (NODE_ENV != production)");
		}
	} else {

		const text = fs.readFileSync(cfgPath, 'utf8');
		if (text) {
			config = JSON.parse(text);
		}

		if (process.env.NODE_ENV != "production") {
			if (!config.jwt || !config.jwt.secret) {
				const buffer = Buffer.alloc(64);
				crypto.randomFillSync(buffer, 0, buffer.length);
				config.jwt.secret = buffer.toString("base64");
				console.warn("Autogenerated JWT secret (NODE_ENV != production)");
			}
		} else {
			if (!config.jwt) {
				config.jwt = {};
			}

			if (!config.jwt.secret) {
				config.jwt.secret = process.env.DOUGAL_JWT_SECRET;
			}
		}

	}

	if (fs.existsSync(globalCfgPath)) {
		const text = fs.readFileSync(globalCfgPath, 'utf8');
		if (text) {
			config.global = YAML.parse(text);
		}
	}

	if (fs.existsSync(usersCfgPath)) {
		const text = fs.readFileSync(usersCfgPath, 'utf8');
		if (text) {
			if (!config.global) {
				config.global = {};
			}
			config.global.users = YAML.parse(text);
		}
	}

} catch (err) {
	console.error(err);
}

if (process.env.PGDATABASE) {
	console.warn("Taking database connection parameters from the environment; 'db' attribute will be removed");
	delete config.db;
}

config.DOUGAL_ROOT = cfgPrefix;
config._ = (k) => k.split(".").reduce((a, b) => typeof a != "undefined" ? a[b] : a, config);

module.exports = Object.freeze(config);
