package main

import (
	"flag"
	"fmt"

	"code.hackerspace.pl/hscloud/go/mirko"
	"github.com/golang/glog"
	"github.com/ybbus/jsonrpc"

	pb "code.hackerspace.pl/hscloud/go/svc/arista-proxy/proto"
)

var (
	flagAristaAPI string
)

type aristaClient struct {
	rpc jsonrpc.RPCClient
}

func (c *aristaClient) structuredCall(res interface{}, command ...string) error {
	cmd := struct {
		Version int      `json:"version"`
		Cmds    []string `json:"cmds"`
		Format  string   `json:"format"`
	}{
		Version: 1,
		Cmds:    command,
		Format:  "json",
	}

	err := c.rpc.CallFor(res, "runCmds", cmd)
	if err != nil {
		return fmt.Errorf("could not execute structured call: %v", err)
	}
	return nil
}

type server struct {
	arista *aristaClient
}

func main() {
	flag.StringVar(&flagAristaAPI, "arista_api", "http://admin:password@1.2.3.4:80/command-api", "Arista remote endpoint")
	flag.Parse()

	arista := &aristaClient{
		rpc: jsonrpc.NewClient(flagAristaAPI),
	}

	m := mirko.New()
	if err := m.Listen(); err != nil {
		glog.Exitf("Listen(): %v", err)
	}

	s := &server{
		arista: arista,
	}
	pb.RegisterAristaProxyServer(m.GRPC(), s)

	if err := m.Serve(); err != nil {
		glog.Exitf("Serve(): %v", err)
	}

	select {}
}
