#!/usr/bin/python3
"""Send one RTSP request to a local shairport-sync and print the response headers.

usage: rtsp-request PORT METHOD PATH [BODY-FILE]

Exits non-zero unless the response status is 200. When BODY-FILE is given the
response body is written there.
"""
import socket
import sys

port, method, path = int(sys.argv[1]), sys.argv[2], sys.argv[3]
body_file = sys.argv[4] if len(sys.argv) > 4 else None

with socket.create_connection(("127.0.0.1", port), timeout=5) as sock:
    sock.sendall(f"{method} {path} RTSP/1.0\r\nCSeq: 1\r\n\r\n".encode("ascii"))
    data = b""
    while b"\r\n\r\n" not in data:
        chunk = sock.recv(4096)
        if not chunk:
            break
        data += chunk
    head, _, body = data.partition(b"\r\n\r\n")
    headers = head.decode("ascii", "replace")
    length = 0
    for line in headers.split("\r\n")[1:]:
        name, _, value = line.partition(":")
        if name.strip().lower() == "content-length":
            length = int(value)
    while len(body) < length:
        chunk = sock.recv(4096)
        if not chunk:
            break
        body += chunk

print(headers)
if body_file:
    with open(body_file, "wb") as f:
        f.write(body)
if not headers.startswith("RTSP/1.0 200 "):
    sys.exit(1)
