const program = require("caporal");

import { dirname, resolve, basename } from "path";
import { expand } from "config-expander";
import { prepareDatabase } from "./database";
import { prepareHttpServer } from "./http";
import { version } from "../package.json";

program
  .description("Konsum server")
  .version(version)
  .option("-c, --config <file>", "use config from file")
  .action(async (args, options, logger) => {
    // some constants used while loading the configuration
    const constants = {
      basedir: dirname(options.config || process.cwd()), // where is the config file located
      installdir: resolve(__dirname, "..") // make references to the installdir possible
    };

    // default config if none is given
    const defaultConfig = {
      database: {
        file: "level.db"
      },
      http: {
        port: 123456
      }
    };

    // load config and expand expressions ${something} inside
    const config = await expand(
      options.config
        ? "${include('" + basename(options.config) + "')}"
        : defaultConfig,
      {
        constants
      }
    );

    // prepare the database with the config
    const db = await prepareDatabase(config);

    // prepare the web-server with the config and the database
    const http = await prepareHttpServer(config, db);
  });

program.parse(process.argv);

@@ -342,20 +342,25 @@
 config %3C
-file
+directory
 %3E%22, %22use
@@ -372,20 +372,25 @@
 ig from 
-file
+directory
 %22)%0A  .ac
@@ -429,16 +429,94 @@
 r) =%3E %7B%0A
+    const configDir = process.env.CONFIGURATION_DIRECTORY %7C%7C options.config;%0A%0A
     // s
@@ -609,30 +609,17 @@
 ir: 
-dirname(options.
 config
+Dir
  %7C%7C 
@@ -631,17 +631,16 @@
 ss.cwd()
-)
 , // whe
@@ -1037,30 +1037,25 @@
 (%0A      
-options.
 config
+Dir
 %0A       
@@ -1077,31 +1077,37 @@
 %22 + 
-basename(options.config
+join(configDir, %22config.json%22
 ) + 

support CONFIGURATION_DIRECTORY (systemd)