package srvhnakra

import "log"
import "fmt"
import "net"
import "crypto/tls"
import "hnakra/router"
import "hnakra/router/config"

type Server struct {
	underlying net.Listener
	Config     config.Config
	Router     *router.Router

	running bool
}

func (server *Server) Run () (err error) {
	server.underlying, err = tls.Listen (
		"tcp", fmt.Sprint(":", server.Config.RouterPort()),
		config.TLSConfigFor(server.Config))
	if err != nil { return err }

	server.running = true
	log.Println(".// router on", server.underlying.Addr())

	for {
		conn, err := server.underlying.Accept()
		if err != nil {
			if server.running {
				return err
			} else {
				return nil
			}
		}
		log.Println("-=E incoming connection from", conn.RemoteAddr())
		server.Router.Accept(conn)
	}
}

func (server *Server) Shutdown () error {
	server.running = false
	return server.underlying.Close()
}
