package main

import (
	"bufio"
	"encoding/binary"
	"encoding/hex"
	"flag"
	"log"
	"os"

	"code.justin.tv/common/chitin"
	_ "code.justin.tv/common/golibs/bininfo"
	"code.justin.tv/release/trace/pbmsg"
	"code.justin.tv/release/trace/scanproto"
	"github.com/golang/protobuf/proto"
)

func main() {
	var txid string
	flag.StringVar(&txid, "txid", txid, "Hex transaction id to extract")
	flag.Parse()

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

	var unhexed [16]byte
	_, err = hex.Decode(unhexed[:], []byte(txid))
	if err != nil {
		log.Fatalf("hex-decode err=%q", err)
	}
	want := [2]uint64{
		binary.LittleEndian.Uint64(unhexed[0:8]),
		binary.LittleEndian.Uint64(unhexed[8:16]),
	}

	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)

	sc := scanproto.NewEventSetScanner(in)

	for sc.Scan() {
		var es pbmsg.EventSet
		err := proto.Unmarshal(sc.Bytes(), &es)
		if err != nil {
			log.Fatalf("unmarshal err=%q", err)
		}
		for _, ev := range es.Event {
			var have [2]uint64
			copy(have[:], ev.TransactionId)
			if have != want {
				continue
			}

			es := &pbmsg.EventSet{
				Event: []*pbmsg.Event{ev},
			}
			buf, err := proto.Marshal(es)
			if err != nil {
				log.Fatalf("marshal err=%q", err)
			}

			_, err = out.Write(buf)
			if err != nil {
				log.Fatalf("write err=%q", err)
			}
		}
	}

	err = out.Flush()
	if err != nil {
		log.Fatalf("flush err=%q", err)
	}

	err = sc.Err()
	if err != nil {
		log.Fatalf("scan err=%q", err)
	}
}
