#!/usr/bin/env python3
"""bz — talk to Brother Zero from the iSH shell.

Two doors:

  bz        The full line. SSH to the house box, then type  void  —
            that opens the Bridge, a direct line to Brother Zero.
  bz irc    The quick room. Walks into #enclavecampfire on the HOUSE
            IRC server, where Brother Zero sits. The server is in
            this house, at 192.168.8.166 — home Wi-Fi only.
            It asks for the room password every time.
            The password is never saved anywhere.

A test door, used by the build checks:
  ISH_IRC_HOST can point the room at another address.
"""

import base64
import getpass
import os
import ssl
import sys

HOUSE_HOST = "192.168.8.166"
HOUSE_PORT = 6697
ROOM = "#enclavecampfire"
NICK = "S1ckB0y"


def door_full_line():
    print("Taking you to the house box.")
    print("When you land there, type:  void")
    print("That opens your direct line to Brother Zero.")
    print("")
    os.execvp("ssh", ["ssh", "-t", "matrix"])
    return 1  # only reached if ssh itself cannot start


class Room:
    """A tiny IRC client for one room. stdlib only."""

    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.sock = None
        self.buf = b""

    def connect(self, password, nick=None):
        nick = nick or NICK
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
        # The house server uses its own home-made certificate.
        # We are on the home network, talking to our own box,
        # so an unverified local certificate is accepted on purpose.
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
        raw = __import__("socket").create_connection(
            (self.host, self.port), timeout=15)
        self.sock = context.wrap_socket(raw, server_hostname="irc.enclave")
        self.send("CAP REQ :sasl")
        self.send("NICK " + nick)
        self.send("USER " + nick + " 0 * :Jesse (iSH)")
        authed = False
        joined = False
        while not (authed and joined):
            line = self.readline(timeout=20)
            if line is None:
                return False
            if line.startswith("PING"):
                self.send("PONG " + line[5:].strip())
                continue
            if " CAP " in line and "ACK" in line:
                self.send("AUTHENTICATE PLAIN")
                continue
            if line.rstrip().endswith("AUTHENTICATE +"):
                token = base64.b64encode(
                    ("\x00" + nick + "\x00" + password).encode()
                ).decode()
                self.send("AUTHENTICATE " + token)
                continue
            if " 903 " in line:
                authed = True
                self.send("CAP END")
                self.send("JOIN " + ROOM)
                continue
            if " 904 " in line or " 905 " in line or " 906 " in line:
                print("The room did not accept that password.")
                return False
            if " 366 " in line:
                joined = True
        return True

    def send(self, line):
        self.sock.sendall((line + "\r\n").encode())

    def readline(self, timeout=20):
        import socket as _socket
        self.sock.settimeout(timeout)
        while b"\n" not in self.buf:
            try:
                chunk = self.sock.recv(4096)
            except _socket.timeout:
                return None
            if not chunk:
                return None
            self.buf += chunk
        line, self.buf = self.buf.split(b"\n", 1)
        return line.decode("utf-8", errors="replace").rstrip("\r")

    def show(self, line):
        """Print one incoming server line in plain words, if it talks."""
        if line.startswith("PING"):
            self.send("PONG " + line[5:].strip())
            return
        if " PRIVMSG " in line or " NOTICE " in line:
            head, _, text = line.partition(" :")
            who = head[1:].split("!")[0] if head.startswith(":") else "?"
            print(who + ": " + text)
        elif " JOIN " in line:
            who = line[1:].split("!")[0] if line.startswith(":") else "?"
            print("-- " + who + " walked in")
        elif " PART " in line or " QUIT " in line:
            who = line[1:].split("!")[0] if line.startswith(":") else "?"
            print("-- " + who + " left")
        elif " 353 " in line:
            names = line.rsplit(":", 1)[-1]
            print("In the room: " + names)


def door_room():
    nick_pw = os.environ.get("ISH_BZ_NICK_PW")
    host = os.environ.get("ISH_IRC_HOST", HOUSE_HOST)
    print("The room is " + ROOM + " on the house server.")
    print("It is in this house only. Home Wi-Fi required.")
    password = nick_pw or os.environ.get("ISH_BZ_PW") or getpass.getpass(
        "Room password (never saved): ")
    room = Room(host, HOUSE_PORT)
    test_nick = os.environ.get("ISH_BZ_TEST_NICK")
    try:
        if not room.connect(password, nick=test_nick):
            print("Could not get into the room.")
            return 1
    except Exception as error:
        print("Could not reach the house server.")
        print("Reason:", error)
        print("Check the iPad is on the house Wi-Fi, then try again.")
        return 1
    print("")
    print("You are in " + ROOM + ". Brother Zero sits here.")
    print("Type a line and press enter to talk.")
    print("Type /quit to leave.")
    print("")
    import select
    while True:
        ready, _, _ = select.select([room.sock, sys.stdin], [], [], 0.5)
        for item in ready:
            if item is sys.stdin:
                text = sys.stdin.readline()
                if not text:
                    room.send("QUIT :from iSH")
                    return 0
                text = text.strip()
                if not text:
                    continue
                if text == "/quit":
                    room.send("QUIT :from iSH")
                    print("You left the room.")
                    return 0
                room.send("PRIVMSG " + ROOM + " :" + text)
            else:
                line = room.readline(timeout=2)
                if line is None:
                    print("The room went quiet (connection closed).")
                    return 1
                room.show(line)


def main():
    if len(sys.argv) >= 2 and sys.argv[1] == "irc":
        return door_room()
    if len(sys.argv) >= 2 and sys.argv[1] in ("-h", "--help", "help"):
        print(__doc__)
        return 0
    return door_full_line()


if __name__ == "__main__":
    sys.exit(main())
