#![cfg_attr(docsrs, feature(doc_cfg))]

use std::net::{Ipv6Addr, SocketAddr, TcpListener};

use socket2::{Domain, Socket, Type};

pub fn listen(port: u16) -> std::io::Result<TcpListener> {
  #[cfg(feature = "listenfd")]
  {
    use listenfd::ListenFd;
    let mut listenfd = ListenFd::from_env();
    if let Some(listener) = listenfd.take_tcp_listener(0)? {
      log::info!("listen from listenfd");
      return Ok(listener);
    }
  }
  let socket = Socket::new(Domain::IPV6, Type::STREAM, None)?;

  socket.set_only_v6(false)?;

  socket.set_nonblocking(true)?;

  let addr = SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), port);
  socket.bind(&addr.into())?;

  socket.listen(1024)?;

  Ok(socket.into())
}
