package main

import (
	"crypto/tls"
	"flag"
	"log"
	"math/rand"
	"net"
	"net/http"
	"time"

	"git.xeserv.us/xena/route/lib/routecrypto"
	"git.xeserv.us/xena/route/server"
	"github.com/Xe/ln"
	"github.com/caarlos0/env"
	"github.com/facebookgo/flagenv"
	_ "github.com/joho/godotenv/autoload"
)

var (
	sslCertKey = flag.String("ssl-cert-key", "", "if set encrypt SSL certs with this key")
)

func main() {
	flag.Parse()
	flagenv.Parse()
	rand.Seed(time.Now().Unix())

	certKey, _ := routecrypto.ParseKey(*sslCertKey)

	scfg := server.Config{}
	err := env.Parse(&scfg)
	if err != nil {
		ln.Fatal(ln.F{"err": err, "action": "env.Parse()"})
	}
	scfg.CertKey = certKey

	s, err := server.New(scfg)
	if err != nil {
		log.Fatal(err)
	}

	go setupTLS(s, scfg)

	l, err := net.Listen("tcp", scfg.WebAddr)
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()

	hs := &http.Server{
		Handler: s,
		Addr:    scfg.WebAddr,
	}

	hs.Serve(l)
}

func setupTLS(s *server.Server, scfg server.Config) {
	hs := &http.Server{
		Handler: s,
		Addr:    scfg.SSLAddr,
		TLSConfig: &tls.Config{
			GetCertificate: s.GetCertificate,
		},
	}

	hs.ListenAndServeTLS("", "")
}
