package quic

import (
	"fmt"
	"syscall"

	"github.com/sagernet/quic-go/internal/protocol"
	"github.com/sagernet/quic-go/internal/utils"
)

//go:generate sh -c "printf '%s\n' '// Code generated by go generate. DO NOT EDIT.' '// Source: sys_conn_buffers.go' '' > sys_conn_buffers_write.go && sed -e 's/setReceiveBuffer/setSendBuffer/g' -e 's/inspectReadBuffer/inspectWriteBuffer/g' -e 's/setReadBufferSize/setWriteBufferSize/g' -e 's/protocol.DesiredReceiveBufferSize/protocol.DesiredSendBufferSize/g' -e 's/forceSetReceiveBuffer/forceSetSendBuffer/g' -e 's/receive buffer/send buffer/g' sys_conn_buffers.go | grep -v '^//go:generate' >> sys_conn_buffers_write.go"
func setReceiveBuffer(c syscall.RawConn) error {
	size, err := inspectReadBuffer(c)
	if err != nil {
		return fmt.Errorf("failed to determine receive buffer size: %w", err)
	}
	if size >= protocol.DesiredReceiveBufferSize {
		utils.DefaultLogger.Debugf("Conn has receive buffer of %d kiB (wanted: at least %d kiB)", size/1024, protocol.DesiredReceiveBufferSize/1024)
		return nil
	}
	// Ignore the error. We check if we succeeded by querying the buffer size afterward.
	_ = setReadBufferSize(c, protocol.DesiredReceiveBufferSize)
	newSize, err := inspectReadBuffer(c)
	if newSize < protocol.DesiredReceiveBufferSize {
		// Try again with RCVBUFFORCE on Linux
		_ = forceSetReceiveBuffer(c, protocol.DesiredReceiveBufferSize)
		newSize, err = inspectReadBuffer(c)
		if err != nil {
			return fmt.Errorf("failed to determine receive buffer size: %w", err)
		}
	}
	if err != nil {
		return fmt.Errorf("failed to determine receive buffer size: %w", err)
	}
	if newSize == size {
		return fmt.Errorf("failed to increase receive buffer size (wanted: %d kiB, got %d kiB)", protocol.DesiredReceiveBufferSize/1024, newSize/1024)
	}
	if newSize < protocol.DesiredReceiveBufferSize {
		return fmt.Errorf("failed to sufficiently increase receive buffer size (was: %d kiB, wanted: %d kiB, got: %d kiB)", size/1024, protocol.DesiredReceiveBufferSize/1024, newSize/1024)
	}
	utils.DefaultLogger.Debugf("Increased receive buffer size to %d kiB", newSize/1024)
	return nil
}
