//go:build !windows

package failover

import (
	"fmt"
	"net"

	"golang.org/x/net/icmp"
)

// NewPinger creates a new pinger with gateway `gateway` and size `size`
func NewPinger(gateway string, size int) (*Pinger, error) {
	gip := net.ParseIP(gateway)
	isV4 := gip.To4() != nil
	mtuOverhead := mtuV6Overhead
	if isV4 {
		mtuOverhead = mtuV4Overhead
	}
	if size < mtuOverhead {
		return nil, fmt.Errorf("invalid MTU size given, MTU has to be at least: %v bytes", mtuOverhead)
	}
	var l *icmp.PacketConn
	var err error
	if isV4 {
		l, err = icmp.ListenPacket("udp4", "0.0.0.0")
	} else {
		l, err = icmp.ListenPacket("udp6", "::")
	}
	if err != nil {
		return nil, fmt.Errorf("failed creating ping with error: %w", err)
	}
	return &Pinger{
		listener: l,
		buffer:   make([]byte, size-mtuOverhead),
		gateway:  &net.UDPAddr{IP: gip},
		v4:       isV4,
	}, nil
}
