//go:build (linux || darwin) && go1.11

package reuseport

import (
	"context"
	"net"
	"syscall"

	"golang.org/x/sys/unix"
)

func Listen(network, address string, reuse bool) (net.Listener, error) {
	if !reuse {
		return net.Listen(network, address)
	}

	lc := net.ListenConfig{
		Control: func(_, _ string, c syscall.RawConn) error {
			var cerr error
			err := c.Control(func(fd uintptr) {
				cerr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1) //nolint:gosec
			})
			if err != nil {
				return err
			}
			return cerr
		},
	}

	return lc.Listen(context.Background(), network, address)
}
