package ebpftracer

import (
	"fmt"

	"github.com/coroot/coroot-node-agent/utils"

	"github.com/cilium/ebpf/link"
)

const (
	// goServeHTTP           = "net/http.serverHandler.ServeHTTP"
	binPath           = "/opt/github/jdk8u/build/linux-x86_64-normal-server-slowdebug/jdk/lib/amd64/libnio.so"
	symbolsocketRead0 = "Java_sun_nio_ch_FileDispatcherImpl_read0"
)

func (t *Tracer) AttachJavaNioReadUprobes(pid uint32, insID utils.ID) []link.Link {
	if t.disableL7Tracing {
		return nil
	}
	var links []link.Link
	ex, err := link.OpenExecutable(binPath)
	if err != nil {
		return nil
	}
	opt := link.UprobeOptions{
		Offset: 103,
		//PID:    int(pid),
	}
	upread02, err := ex.Uprobe(symbolsocketRead0, t.uprobes["uprobe_Java_sun_nio_ch_FileDispatcherImpl_read0"], &opt)
	if err != nil {
		return nil
	}
	links = append(links, upread02)

	if len(links) == 0 {
		return nil
	}
	fmt.Println("jvm uprobes attached")
	return links
}

func (t *Tracer) AttachJavaNetReadUprobes(pid uint32, insID utils.ID) []link.Link {
	if t.disableL7Tracing {
		return nil
	}
	//
	//if pid != 251719 {
	//	return nil
	//}

	var libnetSo = "/opt/github/jdk8u/build/linux-x86_64-normal-server-slowdebug/jdk/lib/amd64/libnet.so"
	var sys = "Java_java_net_SocketOutputStream_socketWrite0"
	var links []link.Link
	ex, err := link.OpenExecutable(libnetSo)
	if err != nil {
		return nil
	}
	opt := link.UprobeOptions{
		Offset: 66,
		PID:    int(pid),
	}
	upread02, err := ex.Uprobe(sys, t.uprobes["uprobe_Java_java_net_SocketOutputStream_socketWrite0"], &opt)
	if err != nil {
		return nil
	}
	links = append(links, upread02)

	if len(links) == 0 {
		return nil
	}
	fmt.Println("jvm client uprobes attached", pid)

	return links
}
