"""
$URL: svn+ssh://sting.mems-exchange.org/repos/trunk/DurusWorks/scgi/scgi_util.py $
$Id: scgi_util.py 32789 2010-09-16 02:01:55Z dbinger $
"""
import socket

def scgi_request(content, **headers):
    """(content:str, **headers) -> str
    This is intended for testing purposes, for use by send_scgi() (below).
    Returns an scgi-formatted request string using the given content and headers.
    """
    headers = '\0'.join(
        ['%s\0%s' % item for item in
         [('CONTENT_LENGTH', len(content)), ('SCGI', 1)] + list(headers.items())])
    s= "%s:%s\0,%s" % (len(headers)+1, headers, content)
    return s.encode('utf-8')

def send_scgi(port, host='localhost', content='',
              PATH_INFO='/', SCRIPT_NAME='', **kwargs):
    """
    This function *only* for testing the response of a running scgi server.
    It sends a request in scgi format and returns the beginning part of the
    response.
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    if content:
        method = "POST"
    else:
        method = "GET"
    s.send(scgi_request(content,
                        REQUEST_METHOD=method,
                        PATH_INFO=PATH_INFO,
                        SCRIPT_NAME=SCRIPT_NAME,
                        **kwargs))
    result = s.recv(1000000)
    s.close()
    return result

if __name__ == '__main__':
    import sys
    if len(sys.argv) < 2:
        print('%s <port> [<PATH_INFO>]' % sys.argv[0])
    elif len(sys.argv) == 2:
        path = '/'
    else:
        path = sys.argv[2]
    port = int(sys.argv[1])
    print(send_scgi(port, PATH_INFO=path))
