package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"net"
	"os"

	"github.com/barakmich/tinkerbell/ray_rpc"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/grpclog"
)

var (
	gRPCPort = flag.Int("grpc-port", 50050, "The gRPC server port")
	httpPort = flag.Int("http-port", 8080, "The HTTP server port")
	webRoot  = flag.String("web-root", "web", "path to static web files")
)

var log grpclog.LoggerV2

func init() {
	log = grpclog.NewLoggerV2(os.Stdout, ioutil.Discard, ioutil.Discard)
	grpclog.SetLoggerV2(log)
}

func main() {
	flag.Parse()
	logger, _ := zap.NewDevelopment()
	zap.ReplaceGlobals(logger)
	addr := fmt.Sprintf("0.0.0.0:%d", *gRPCPort)
	lis, err := net.Listen("tcp", addr)
	if err != nil {
		logger.Fatal("Failed to listen:", zap.Error(err))
	}
	s := grpc.NewServer(
		grpc.Creds(insecure.NewCredentials()),
	)
	server := NewMemRaylet()
	ray_rpc.RegisterRayletDriverServer(s, server)
	ray_rpc.RegisterRayletWorkerConnectionServer(s, server)
	go runHttp(fmt.Sprintf("0.0.0.0:%d", *httpPort), *webRoot, server)

	// Serve gRPC Server
	fmt.Println("Serving gRPC on https://", addr)
	s.Serve(lis)
}
