package main

import (
	"flag"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	"code.justin.tv/common/chitin"
	_ "code.justin.tv/common/golibs/bininfo"
	"code.justin.tv/release/trace/pbmsg"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

var (
	serverHostPort = flag.String("server", "trace-api.prod.us-west2.justin.tv:11143", "The server hostport")
	service        = flag.String("svc", "code.justin.tv/web/web", "The service to analyze")
	sampling       = flag.Float64("sample", 0.1, "Sampling rate")
	duration       = flag.Duration("t", time.Second, "How long to capture data before returning a result")
)

func main() {
	flag.Parse()

	err := chitin.ExperimentalTraceProcessOptIn()
	if err != nil {
		log.Fatalf("trace enable err=%q", err)
	}

	conn, err := grpc.Dial(*serverHostPort, grpc.WithInsecure())
	if err != nil {
		log.Fatalf("fail to dial: %v", err)
	}
	defer conn.Close()
	client := pbmsg.NewTraceClient(conn)
	ctx, cancel := context.WithTimeout(context.Background(), *duration)

	log.Println("turning on signal handling")
	sigch := make(chan os.Signal, 1)
	signal.Notify(sigch, syscall.SIGINT)
	go func() {
		for _ = range sigch {
			log.Println("Canceling context...")
			cancel()
		}
	}()

	firehose, err := client.Firehose(ctx, &pbmsg.FirehoseRequest{
		Sampling: *sampling,
		Query: &pbmsg.Query{
			Comparisons: []*pbmsg.Comparison{
				&pbmsg.Comparison{
					ServiceName: &pbmsg.StringComparison{Value: *service},
				},
			},
		},
	})
	if err != nil {
		log.Fatalf("%v.Firehose(_) = _, %v", client, err)
	}

	result := consumeFirehose(firehose)
	if err := dump(result, os.Stdout); err != nil {
		log.Fatalf("dump err=%q", err)
	}

}
