package ebpftracer

import (
	"fmt"

	"github.com/cilium/ebpf"
	"github.com/cilium/ebpf/link"
	"github.com/coroot/coroot-node-agent/ebpftracer/tracer"
)

func (t *Tracer) AttachStackUprobes(path string, uprobes []tracer.Uprobe) []link.Link {
	var links []link.Link

	ex, err := link.OpenExecutable(path)
	if err != nil {
		return nil
	}
	fmt.Println("Attach Start", path)

	for i, up := range uprobes {
		fmt.Printf("attaching %d -> %d -> %s -> 0x%x -> 0x%x -> 0x%x\n", i, len(uprobes), up.Funcname, up.AbsOffset, up.Address, up.AbsOffset+up.Address)
		var prog *ebpf.Program
		switch up.Location {
		case tracer.AtEntry:
			prog = t.uprobes["ent"]
		case tracer.AtRet:
			prog = t.uprobes["ret"]
		case tracer.AtDotNetEntry:
			prog = t.uprobes["dotnetent"]
		}
		uplink, err := ex.Uprobe(up.Funcname, prog, &link.UprobeOptions{Address: up.Address, Offset: up.AbsOffset})
		if err != nil {
			fmt.Printf("attachingERROR:%v, %v, %v\n", err, up, uplink)
			// return nil
		} else {
			links = append(links, uplink)
		}
	}
	return links
}
