package main

import (
	"flag"
	"io/fs"
	"log"
	"net/http"
	"os"
	"os/signal"
	"path"
	"path/filepath"
	"syscall"

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

var DashboardDir string
var TeamsDir string

func main() {
	var baseURL string
	// 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:8082", "Bind port/socket")
	htpasswd_file := flag.String("htpasswd", "", "Restrict access with password, Apache htpasswd format")
	restrict_ip := flag.String("restrict-to-ips", "", "Restrict access to IP listed in this JSON array")
	flag.StringVar(&baseURL, "baseurl", baseURL, "URL prepended to each URL")
	staticDir := flag.String("static", "./htdocs-dashboard/", "Directory containing static files")
	flag.StringVar(&fic.FilesDir, "files", fic.FilesDir, "Base directory where found challenges files, local part")
	flag.StringVar(&DashboardDir, "dashbord", "./DASHBOARD", "Base directory where save public JSON files")
	flag.StringVar(&TeamsDir, "teams", "./TEAMS", "Base directory where save teams JSON files")
	flag.StringVar(&settings.SettingsDir, "settings", "./SETTINGSDIST", "Base directory where load and save settings")
	var fwdr = flag.String("forwarder", "", "URL of another dashboard where send traffic to, except static assets")
	flag.BoolVar(&fwdPublicJson, "fwdpublicjson", fwdPublicJson, "Also forward public.json files to forwarder")
	flag.Parse()

	log.SetPrefix("[public] ")

	// Sanitize options
	var err error
	log.Println("Checking paths...")
	if staticDir != nil && *staticDir != "" {
		if sDir, err := filepath.Abs(*staticDir); err != nil {
			log.Fatal(err)
		} else {
			log.Println("Serving pages from", sDir)
			staticFS = http.Dir(sDir)
		}
	} else {
		sub, err := fs.Sub(assets, "static")
		if err != nil {
			log.Fatal("Unable to cd to static/ directory:", err)
		}
		log.Println("Serving pages from memory.")
		staticFS = http.FS(sub)
	}
	if fic.FilesDir, err = filepath.Abs(fic.FilesDir); err != nil {
		log.Fatal(err)
	}
	if settings.SettingsDir, err = filepath.Abs(settings.SettingsDir); err != nil {
		log.Fatal(err)
	}
	if baseURL != "/" {
		baseURL = path.Clean(baseURL)
	} else {
		baseURL = ""
	}
	if fwdr != nil && len(*fwdr) > 0 {
		forwarder = fwdr
	}

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

	app := NewApp(htpasswd_file, restrict_ip, baseURL, *bind)
	go app.Start()

	// Wait shutdown signal
	<-interrupt

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