package tracer

import (
	"fmt"
	"github.com/cilium/ebpf"
	"github.com/cilium/ebpf/asm"
	"os"
	"strconv"
)

func PidFilter(collectionSpec *ebpf.CollectionSpec) {
	ENV_PID := os.Getenv("FILTER_PID")
	if ENV_PID != "" {
		filterPid, _ := strconv.ParseInt(ENV_PID, 10, 64)
		type Editor struct {
			instructions     *asm.Instructions
			ReferenceOffsets map[string][]int
		}
		for _, prog := range collectionSpec.Programs {
			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 = filterPid
			}
		}
	}
}
