#!/bin/env python

# Python imports
import sys
import base64
from multiprocessing.connection import Client

# Lib imports

# Application imports



APP_NAME = "Newton"
address = f"/tmp/{APP_NAME}-ipc.sock"
authkey = f"{APP_NAME}-ipc".encode()



def send_command(command: str, receive: bool = False):
    conn = Client(address, family = "AF_UNIX", authkey = authkey)

    try:
        conn.send(command)
        if receive:
            return conn.recv()
    except EOFError:
        print("Server disconnected", file=sys.stderr)

    finally:
        conn.close()


def do_commands():
    for command in sys.argv[1:]:
        if command.lower() in ("exit", "quit", "q"):
            break

        print("Command:", command)
        response = send_command(
            command,
            receive = (command.lower() == "opipe")
        )

        if response is not None:
            print(response)


def main():
    if not sys.stdin.isatty():
        command = sys.stdin.read().strip()
        encoded = base64.b64encode(command.encode()).decode()

        if not encoded: return

        response = send_command(f"IPIPE|{encoded}", receive = True)
        if response is not None:
            print(response)

        return

    do_commands()


if __name__ == "__main__":
    main()
