use anyhow::{Context, Result};
use mdns_sd::{ServiceDaemon, ServiceInfo};
const SERVICE_TYPE: &str = "_grod._tcp.local.";
pub fn publish(lan_host: &str, api_port: u16, pin_required: bool) -> Result<ServiceDaemon> {
let mdns = ServiceDaemon::new().context("failed to start mDNS daemon")?;
let hostname = format!("grod-{}.local.", sanitize_for_hostname(lan_host));
let instance_name = "grod";
let mut props = std::collections::HashMap::new();
props.insert("version".to_string(), env!("CARGO_PKG_VERSION").to_string());
props.insert("pin".to_string(), if pin_required { "1" } else { "0" }.to_string());
let info = ServiceInfo::new(
SERVICE_TYPE,
instance_name,
&hostname,
lan_host,
api_port,
Some(props),
)
.context("building mDNS ServiceInfo")?;
mdns.register(info)
.context("registering mDNS service")?;
eprintln!(
"[daemon] mDNS service registered: {instance_name}.{SERVICE_TYPE} on {lan_host}:{api_port}"
);
Ok(mdns)
}
fn sanitize_for_hostname(ip: &str) -> String {
ip.replace('.', "-").replace(':', "-")
}