// Package params provides helpers for receiving setup payload from parent.
package params

import (
	"encoding/gob"
	"errors"
	"os"
	"strconv"
	"syscall"
)

// ErrReceiveEnv is returned by [Receive] if setup fd is not present in environment.
var ErrReceiveEnv = errors.New("environment variable not set")

// Receive retrieves setup fd from the environment and receives params.
//
// The file descriptor written to the value pointed to by fdp must not be passed
// to any system calls. It is made available for ordering file descriptor only.
func Receive(key string, v any, fdp *int) (func() error, error) {
	var setup *os.File

	if s, ok := os.LookupEnv(key); !ok {
		return nil, ErrReceiveEnv
	} else {
		if fd, err := strconv.Atoi(s); err != nil {
			if _err := errors.Unwrap(err); _err != nil {
				err = _err
			}
			return nil, err
		} else {
			setup = os.NewFile(uintptr(fd), "setup")
			if setup == nil {
				return nil, syscall.EDOM
			}
			if fdp != nil {
				*fdp = fd
			}
		}
	}

	return setup.Close, gob.NewDecoder(setup).Decode(v)
}
