import socket


def send_all(s, text, stutdown_after_sending=True):
    """send_all(socket, text, stutdown_after_sending=True)

    Send all text to the socket. Used during handshaking and in
    the clientserver module.

    If stutdown_after_sending, the socket is shut down. Some protocols
    rely on this.

    It is made sure that the text ends with a CRLF double-newline code.

    """

    # Ensure closing chars
    if not text.endswith("\r\n"):
        text += "\r\n"

    # Make bytes
    bb = text.encode("utf-8")

    # Send all bytes
    try:
        s.sendall(bb)  # -> n
    except socket.error:
        return -1  # Socket closed down badly

    # Shutdown connection nicely from here
    if stutdown_after_sending:
        try:
            s.shutdown(socket.SHUT_WR)
        except socket.error:
            pass