package main

import (
	"context"
	"log"
	"os"

	sr "tildegit.org/tjp/sliderule"
	"tildegit.org/tjp/sliderule/contrib/fs"
	"tildegit.org/tjp/sliderule/gemini"
	"tildegit.org/tjp/sliderule/logging"
)

func main() {
	// Get TLS files from the environment
	certfile, keyfile := envConfig()

	// build a TLS configuration suitable for gemini
	tlsconf, err := gemini.FileTLS(certfile, keyfile)
	if err != nil {
		log.Fatal(err)
	}

	// build the request handler
	fileSystem := os.DirFS(".")
	// Fallthrough tries each handler in succession until it gets something other than "51 Not Found"
	handler := sr.FallthroughHandler(
		// first see if they're fetching a directory and we have <dir>/index.gmi
		fs.GeminiDirectoryDefault(fileSystem, "index.gmi"),
		// next (still if they requested a directory) build a directory listing response
		fs.GeminiDirectoryListing(fileSystem, nil),
		// finally, try to find a file at the request path and respond with that
		fs.GeminiFileHandler(fileSystem),
	)

	router := &sr.Router{}
	router.Route("/*", handler)
	handler = router.Handler()

	_, infoLog, _, errLog := logging.DefaultLoggers()

	// add request logging to stdout
	handler = logging.LogRequests(infoLog)(handler)

	// run the server
	server, err := gemini.NewServer(context.Background(), "localhost", "tcp4", ":1965", handler, errLog, tlsconf)
	if err != nil {
		log.Fatal(err)
	}
	server.Serve()
}

func envConfig() (string, string) {
	certfile, ok := os.LookupEnv("SERVER_CERTIFICATE")
	if !ok {
		log.Fatal("missing SERVER_CERTIFICATE environment variable")
	}

	keyfile, ok := os.LookupEnv("SERVER_PRIVATEKEY")
	if !ok {
		log.Fatal("missing SERVER_PRIVATEKEY environment variable")
	}

	return certfile, keyfile
}