package main

import (
	"flag"
	"log"
	"os"
	"os/signal"
	"path"
	"syscall"

	"srs.epita.fr/fic-server/libfic"
	"srs.epita.fr/fic-server/qa/api"
	"srs.epita.fr/fic-server/settings"
)

func reloadSettings(config *settings.Settings) {
	api.ManagerUsers = config.DelegatedQA
}

func main() {
	// Read paremeters from environment
	if v, exists := os.LookupEnv("FIC_BASEURL"); exists {
		BaseURL = v
	}

	// Read parameters from command line
	var bind = flag.String("bind", "127.0.0.1:8083", "Bind port/socket")
	var dsn = flag.String("dsn", fic.DSNGenerator(), "DSN to connect to the MySQL server")
	flag.StringVar(&BaseURL, "baseurl", BaseURL, "URL prepended to each URL")
	flag.StringVar(&DevProxy, "dev", DevProxy, "Proxify traffic to this host for static assets")
	flag.StringVar(&settings.SettingsDir, "settings", "./SETTINGSDIST", "Base directory where load and save settings")
	flag.StringVar(&api.TeamsDir, "teams", "./TEAMS", "Base directory where save teams JSON files")
	flag.StringVar(&api.Simulator, "simulator", "", "Auth string to simulate (for development only)")
	flag.Parse()

	log.SetPrefix("[qa] ")

	// Sanitize options
	var err error
	log.Println("Checking paths...")
	if BaseURL != "/" {
		BaseURL = path.Clean(BaseURL)
	} else {
		BaseURL = ""
	}
	if err = sanitizeStaticOptions(); err != nil {
		log.Fatal(err)
	}
	if api.Simulator != "" {
		if _, err := os.Stat(path.Join(api.TeamsDir, api.Simulator)); os.IsNotExist(err) {
			log.Fatal(err)
		}
	}

	// Load configuration
	settings.LoadAndWatchSettings(path.Join(settings.SettingsDir, settings.SettingsFile), reloadSettings)

	// Database connection
	log.Println("Opening database...")
	if err = fic.DBInit(*dsn); err != nil {
		log.Fatal("Cannot open the database: ", err)
	}
	defer fic.DBClose()

	a := NewApp(BaseURL)
	go a.Start(*bind)

	// Prepare graceful shutdown
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)

	// Wait shutdown signal
	<-interrupt

	log.Print("The service is shutting down...")
	a.Stop()
	log.Println("done")
}
