package discovery

import (
	"context"
	"net"
	"strings"
	"time"
)

func Serve(ctx context.Context, port int, grpcAddr string) error {
	conn, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero, Port: port})
	if err != nil {
		return err
	}
	defer conn.Close()

	buf := make([]byte, 256)
	for {
		if err := conn.SetReadDeadline(time.Now().Add(time.Second)); err != nil {
			return err
		}

		n, remote, err := conn.ReadFromUDP(buf)
		if err != nil {
			if ne, ok := err.(net.Error); ok && ne.Timeout() {
				select {
				case <-ctx.Done():
					return nil
				default:
					continue
				}
			}
			return err
		}

		if strings.TrimSpace(string(buf[:n])) != requestMagic {
			continue
		}

		_, _ = conn.WriteToUDP([]byte(responsePrefix+grpcAddr), remote)
	}
}
