package mdnsserver

import (
	"context"
	"log"

	"github.com/godbus/dbus/v5"
	"github.com/holoplot/go-avahi"
)

func Run(ctx context.Context) {
	conn, err := dbus.SystemBus()
	if err != nil {
		return
	}
	a, err := avahi.ServerNew(conn)
	if err != nil {
		log.Fatalf("Avahi new failed: %v", err)
	}

	eg, err := a.EntryGroupNew()
	if err != nil {
		log.Fatalf("EntryGroupNew() failed: %v", err)
	}

	hostname, err := a.GetHostName()
	if err != nil {
		log.Fatalf("GetHostName() failed: %v", err)
	}

	fqdn, err := a.GetHostNameFqdn()
	if err != nil {
		log.Fatalf("GetHostNameFqdn() failed: %v", err)
	}

	err = eg.AddService(avahi.InterfaceUnspec, avahi.ProtoUnspec, 0, hostname, "_my-nifty-service._tcp", "local", fqdn, 1234, nil)
	if err != nil {
		log.Fatalf("AddService() failed: %v", err)
	}

	err = eg.Commit()
	if err != nil {
		log.Fatalf("Commit() failed: %v", err)
	}

	<-ctx.Done()
	eg.Reset()
	conn.Close()
}
