package tracer

import (
	"github.com/cilium/ebpf"
	"github.com/cilium/ebpf/asm"
	"github.com/coroot/coroot-node-agent/common"
)

func PidFilter(collectionSpec *ebpf.CollectionSpec) {
	filterPid, isZero := common.GetFilterPid()
	if !isZero {
		type Editor struct {
			instructions     *asm.Instructions
			ReferenceOffsets map[string][]int
		}
		for _, prog := range collectionSpec.Programs {
			//klog.Infof("[%v] [%v] [%v]", prog.Type, prog.Name, prog.SectionName)
			//fmt.Println("collectionSpec.Program:", prog.Name, prog.SectionName, prog.Type)
			insns := &prog.Instructions
			refs := insns.ReferenceOffsets()

			edit := &Editor{insns, refs}
			indices := edit.ReferenceOffsets["filter_pid"]
			//fmt.Println("len(indices):", len(indices))
			if len(indices) == 0 {
				continue
			}
			ldDWImm := asm.LoadImmOp(asm.DWord)
			for _, index := range indices {
				load := &(*edit.instructions)[index]
				if load.OpCode != ldDWImm {
					continue
					//return errors.Errorf("symbol %v: load: found %v instead of %v", symbol, load.OpCode, ldDWImm)
				}
				load.Constant = int64(filterPid)
			}
		}
	}
}
