aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/byspel/app/App.scala
blob: 15a216ffeb36c69404f8844e35bf7c02eabec3d6 (plain) (blame)
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
package byspel
package app

import akka.actor.ActorSystem
import akka.stream.{ActorMaterializer, Materializer}
import java.nio.file.{Files, Paths}
import scala.concurrent.ExecutionContext
import toml.Toml

trait App {

  implicit lazy val system: ActorSystem = ActorSystem()

  implicit lazy val materializer: Materializer = ActorMaterializer()

  implicit lazy val executionContext: ExecutionContext = system.dispatcher

  def start(): Unit = {}
  def stop(): Unit = {}

  def log(msg: String) = System.err.println(msg)

  private var _args: List[String] = Nil
  def args = _args

  lazy val config = args match {
    case Nil =>
      log("fatal: no config file given as first argument")
      sys.exit(1)
    case head :: _ if Files.isReadable(Paths.get(head)) =>
      log(s"loading config from '${args(0)}'")
      import toml.Codecs._
      val str = new String(Files.readAllBytes(Paths.get(head)), "utf-8")
      Toml.parseAs[Config](str) match {
        case Left(err) =>
          log(s"fatal: syntax error in config file: $err")
          sys.exit(1)
        case Right(value) => value
      }
    case head :: _ =>
      log(s"fatal: config file '$head' is not readable or does not exist")
      sys.exit(1)
  }

  def main(args: Array[String]): Unit = {
    log("starting application")
    _args = args.toList
    config
    sys.addShutdownHook {
      log("stopping application")
      stop()
      log("bye")
    }
    start()
    log("ready")
  }

}