#!/usr/bin/python3
""" Process an incoming connection. """

import os
import select
import socket


def main() -> None:
    """ Main program: poll the sockets, send out a line. """
    assert os.getenv('LISTEN_FDS') == '2'
    fdnamelist = os.getenv('LISTEN_FDNAMES')
    assert fdnamelist is not None
    fdnames = {
        item[0] + 3: item[1] for item in enumerate(fdnamelist.split(':'))
    }

    spoll = select.poll()
    for sock in fdnames.keys():
        spoll.register(sock, select.POLLIN | select.POLLHUP | select.POLLERR)

    res = spoll.poll()
    for listensock, event in res:
        if not event & select.POLLIN:
            continue

        sdomain, sname = fdnames[listensock].split('-', maxsplit=1)
        sfamily = {
            'i': socket.AF_INET,
            'u': socket.AF_UNIX,
        }[sdomain]
        stype = {
            'mellon': socket.SOCK_STREAM,
            'friend': socket.SOCK_DGRAM,
        }[sname]
        lsock = socket.socket(fileno=listensock, family=sfamily, type=stype)
        if lsock.family != socket.AF_INET or lsock.type != socket.SOCK_DGRAM:
            (conn, _) = lsock.accept()
        else:
            (_, addrinfo) = lsock.recvfrom(4096)
            lsock.connect(addrinfo)
            conn = lsock

        conn.send((sname + '\n').encode('ascii'))


if __name__ == '__main__':
    main()
