package main

import (
  "log"
  "os"
  "os/signal"
  "syscall"
  "github.com/gofiber/fiber/v2"
  "github.com/gofiber/fiber/v2/middleware/logger"
  "github.com/gofiber/template/html/v2"

  _ "github.com/mattn/go-sqlite3"
  recov "github.com/gofiber/fiber/v2/middleware/recover"

  "MY/webapp/api"
  "MY/webapp/data"
  "MY/webapp/config"
  "MY/webapp/admin"
)

func main() {
  config.Load("config.toml")
  log.Printf("ADMIN is %s", config.Settings.Admin)

  log.SetFlags(log.LstdFlags | log.Lshortfile)

  engine := html.New(config.Settings.Views, ".html")
  engine.Reload(true)

  app := fiber.New(fiber.Config{
    Views: engine,
    ViewsLayout: config.Settings.Layouts,
    CaseSensitive: true,
    StrictRouting: true,
  })

  app.Use(logger.New())
  app.Use(recov.New())

  data.Setup(config.Settings.Database.Driver, config.Settings.Database.Url)
  api.Setup(app)
  admin.Setup(app)

  // this sets up graceful shutdown
  go func() {
	  if err := app.Listen(config.Settings.Port); err != nil {
		  log.Panic(err)
	  }
  }()

  c := make(chan os.Signal, 1)
  signal.Notify(c, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)

  _ = <-c
  log.Println("Shutdown now...")
  _ = app.Shutdown()

  api.Shutdown()
  data.Shutdown()

  log.Println("Done.")
}
