#!/usr/bin/env python3
"""deckpad: turn phones into Xbox 360 controllers for a Linux PC / Steam Deck.

Phones open http://<this machine>:8777 in a browser, type the code this prints,
and each phone becomes its own virtual Xbox 360 pad (via /dev/uinput), so
Steam and SDL games see a normal controller. Python 3 standard library only.
"""
import argparse, base64, fcntl, hashlib, json, os, secrets, socket, struct, sys, threading, time
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs

HERE = os.path.dirname(os.path.abspath(__file__))
CONF = os.path.join(os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')), 'deckpad')

# linux/uinput.h (values checked against the kernel headers on x86_64)
UI_SET_EVBIT, UI_SET_KEYBIT, UI_SET_ABSBIT = 0x40045564, 0x40045565, 0x40045567
UI_DEV_SETUP, UI_ABS_SETUP = 0x405c5503, 0x401c5504
UI_DEV_CREATE, UI_DEV_DESTROY = 0x5501, 0x5502
EV_SYN, EV_KEY, EV_ABS = 0, 1, 3

# bit i of the phone's button mask -> evdev key, in the layout the xpad driver uses
BUTTONS = [0x130, 0x131, 0x133, 0x134,   # A B X Y
           0x136, 0x137,                 # LB RB
           0x13a, 0x13b, 0x13c,          # Back Start Guide
           0x13d, 0x13e]                 # L3 R3
# state[1:] from the phone -> (axis code, min, max, fuzz, flat)
AXES = [(0x00, -32768, 32767, 16, 128), (0x01, -32768, 32767, 16, 128),   # left stick
        (0x03, -32768, 32767, 16, 128), (0x04, -32768, 32767, 16, 128),   # right stick
        (0x02, 0, 255, 0, 0), (0x05, 0, 255, 0, 0),                       # LT RT
        (0x10, -1, 1, 0, 0), (0x11, -1, 1, 0, 0)]                         # d-pad
NAME = b'Microsoft X-Box 360 pad'


class Pad:
    """One virtual controller. state = [buttons, lx, ly, rx, ry, lt, rt, hatx, haty]."""

    def __init__(self, fake=False):
        self.state = [0] * 9
        self.fd = None
        self.fake = fake
        if fake:
            return
        fd = os.open('/dev/uinput', os.O_WRONLY | os.O_NONBLOCK)
        try:
            fcntl.ioctl(fd, UI_SET_EVBIT, EV_KEY)
            fcntl.ioctl(fd, UI_SET_EVBIT, EV_ABS)
            for b in BUTTONS:
                fcntl.ioctl(fd, UI_SET_KEYBIT, b)
            for code, lo, hi, fuzz, flat in AXES:
                fcntl.ioctl(fd, UI_SET_ABSBIT, code)
                fcntl.ioctl(fd, UI_ABS_SETUP, struct.pack('=H2x6i', code, 0, lo, hi, fuzz, flat, 0))
            # struct uinput_setup: input_id {bustype, vendor, product, version}, name[80], ff_effects_max
            fcntl.ioctl(fd, UI_DEV_SETUP, struct.pack('=4H80sI', 0x03, 0x045e, 0x028e, 0x0114, NAME, 0))
            fcntl.ioctl(fd, UI_DEV_CREATE)
        except OSError:
            os.close(fd)
            raise
        self.fd = fd

    def set(self, new):
        """Apply a new state, emitting only what changed."""
        ev = []
        if new[0] != self.state[0]:
            for i, key in enumerate(BUTTONS):
                bit = (new[0] >> i) & 1
                if bit != (self.state[0] >> i) & 1:
                    ev.append((EV_KEY, key, bit))
        for i, (code, lo, hi, _, _) in enumerate(AXES):
            v = max(lo, min(hi, new[i + 1]))
            new[i + 1] = v
            if v != self.state[i + 1]:
                ev.append((EV_ABS, code, v))
        self.state = new
        if ev:
            ev.append((EV_SYN, 0, 0))
            self.write(ev)

    def write(self, ev):
        if self.fake:
            log(f'events {ev}')
            return
        # struct input_event: struct timeval (kernel fills in the time), type, code, value
        os.write(self.fd, b''.join(struct.pack('=qqHHi', 0, 0, t, c, v) for t, c, v in ev))

    def release(self):
        self.set([0] * 9)

    def close(self):
        if self.fd is not None:
            try:
                self.release()
                fcntl.ioctl(self.fd, UI_DEV_DESTROY)
            finally:
                os.close(self.fd)
                self.fd = None


class Pool:
    """Pads keyed by the phone's id, so a phone that drops off Wi-Fi gets its
    same controller (and player number) back when it reconnects."""
    KEEP = 120  # seconds an unused pad sticks around

    def __init__(self, size, fake):
        self.size, self.fake = size, fake
        self.slots = [None] * size   # slot -> {'id', 'pad', 'conns', 'left'}
        self.lock = threading.Lock()
        threading.Thread(target=self.reap, daemon=True).start()

    def claim(self, cid):
        with self.lock:
            for i, s in enumerate(self.slots):
                if s and s['id'] == cid:
                    s['conns'] += 1
                    return i, s['pad']
            free = [i for i, s in enumerate(self.slots) if s is None]
            if not free:   # reuse the pad that has been idle longest
                idle = [i for i, s in enumerate(self.slots) if s['conns'] == 0]
                if not idle:
                    return None, None
                i = min(idle, key=lambda i: self.slots[i]['left'])
                self.slots[i]['pad'].close()
                self.slots[i] = None
                free = [i]
            i = free[0]
            pad = Pad(self.fake)
            self.slots[i] = {'id': cid, 'pad': pad, 'conns': 1, 'left': 0}
            return i, pad

    def drop(self, slot):
        with self.lock:
            s = self.slots[slot]
            s['conns'] -= 1
            if s['conns'] == 0:
                s['pad'].release()
                s['left'] = time.time()

    def reap(self):
        while True:
            time.sleep(10)
            with self.lock:
                for i, s in enumerate(self.slots):
                    if s and s['conns'] == 0 and time.time() - s['left'] > self.KEEP:
                        s['pad'].close()
                        self.slots[i] = None
                        log(f'player {i + 1} removed (idle)')

    def close(self):
        with self.lock:
            for s in self.slots:
                if s:
                    s['pad'].close()


def log(msg):
    print(time.strftime('%H:%M:%S'), msg, flush=True)


# ---------- minimal WebSocket (RFC 6455), enough for small text frames ----------

def ws_recv(sock):
    """Return (opcode, payload) or raise ConnectionError."""
    def need(n):
        buf = b''
        while len(buf) < n:
            try:
                chunk = sock.recv(n - len(buf))
            except socket.timeout:
                if not buf:
                    raise
                continue   # halfway through a frame: keep waiting for the rest
            if not chunk:
                raise ConnectionError('closed')
            buf += chunk
        return buf
    b1, b2 = need(2)
    n = b2 & 0x7f
    if n == 126:
        n = struct.unpack('>H', need(2))[0]
    elif n == 127:
        n = struct.unpack('>Q', need(8))[0]
    if n > 4096:
        raise ConnectionError('frame too big')
    mask = need(4) if b2 & 0x80 else b'\0\0\0\0'
    data = bytes(c ^ mask[i % 4] for i, c in enumerate(need(n)))
    return b1 & 0x0f, data


def ws_send(sock, data, op=1):
    if isinstance(data, str):
        data = data.encode()
    n = len(data)
    head = bytes([0x80 | op, n]) if n < 126 else bytes([0x80 | op, 126]) + struct.pack('>H', n)
    sock.sendall(head + data)


class Handler(BaseHTTPRequestHandler):
    server_version = 'deckpad'
    protocol_version = 'HTTP/1.1'   # browsers reject a WebSocket upgrade answered with HTTP/1.0

    def log_message(self, *a):
        pass

    def do_GET(self):
        url = urlparse(self.path)
        if url.path == '/ws':
            return self.websocket(parse_qs(url.query))
        if url.path in ('/', '/index.html'):
            body = self.server.page
            self.send_response(200)
            self.send_header('Content-Type', 'text/html; charset=utf-8')
            self.send_header('Content-Length', str(len(body)))
            self.send_header('Cache-Control', 'no-store')
            self.end_headers()
            self.wfile.write(body)
            return
        self.send_error(404)

    def websocket(self, q):
        key = self.headers.get('Sec-WebSocket-Key')
        if not key or self.headers.get('Upgrade', '').lower() != 'websocket':
            return self.send_error(400)
        accept = base64.b64encode(hashlib.sha1((key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').encode()).digest())
        self.send_response(101)
        self.send_header('Upgrade', 'websocket')
        self.send_header('Connection', 'Upgrade')
        self.send_header('Sec-WebSocket-Accept', accept.decode())
        self.end_headers()
        self.wfile.flush()
        sock = self.connection
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        who = self.client_address[0]

        if not secrets.compare_digest(q.get('k', [''])[0].strip(), self.server.code):
            log(f'{who}: wrong code')
            ws_send(sock, json.dumps({'error': 'code'}))
            ws_send(sock, b'', 8)
            return
        cid = q.get('id', [''])[0][:64] or who
        try:
            slot, pad = self.server.pool.claim(cid)
        except OSError as e:
            log(f'{who}: cannot create controller: {e}')
            ws_send(sock, json.dumps({'error': 'uinput', 'detail': str(e)}))
            ws_send(sock, b'', 8)
            return
        if slot is None:
            ws_send(sock, json.dumps({'error': 'full'}))
            ws_send(sock, b'', 8)
            return
        log(f'{who}: connected as player {slot + 1}')
        ws_send(sock, json.dumps({'player': slot + 1}))
        sock.settimeout(1.0)   # phones send a heartbeat every 250 ms
        quiet = 0
        try:
            while True:
                try:
                    op, data = ws_recv(sock)
                except socket.timeout:
                    pad.release()          # phone went quiet: let go of everything
                    quiet += 1
                    if quiet >= 10:
                        break
                    continue
                quiet = 0
                if op == 8:
                    break
                if op == 9:
                    ws_send(sock, data, 10)
                    continue
                if op != 1:
                    continue
                try:
                    st = json.loads(data)
                    if isinstance(st, list) and len(st) == 9:
                        pad.set([int(v) for v in st])
                except (ValueError, TypeError):
                    pass
                except OSError as e:   # a uinput write problem shouldn't drop the phone
                    log(f'{who}: controller write failed: {e!r}')
            why = 'phone went quiet' if quiet else 'phone closed'
        except (ConnectionError, OSError) as e:
            why = repr(e)
        finally:
            self.server.pool.drop(slot)
        log(f'{who}: player {slot + 1} disconnected ({why})')
        self.close_connection = True


def lan_addresses():
    addrs = set()
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('10.255.255.255', 1))   # no packet is sent; just picks the LAN interface
        addrs.add(s.getsockname()[0])
        s.close()
    except OSError:
        pass
    return sorted(a for a in addrs if not a.startswith('127.'))


def load_code(fixed):
    if fixed:
        return fixed
    path = os.path.join(CONF, 'code')
    try:
        with open(path) as f:
            c = f.read().strip()
            if c:
                return c
    except FileNotFoundError:
        pass
    c = f'{secrets.randbelow(10000):04d}'
    os.makedirs(CONF, exist_ok=True)
    with open(path, 'w') as f:
        f.write(c + '\n')
    return c


def check_uinput():
    if not os.path.exists('/dev/uinput'):
        return 'no /dev/uinput (try: sudo modprobe uinput)'
    if not os.access('/dev/uinput', os.W_OK):
        return ('no permission to write /dev/uinput. Fix (Steam Deck: set a password with `passwd` first):\n'
                f'    sudo setfacl -m u:{os.environ.get("USER", "deck")}:rw /dev/uinput   # until reboot\n'
                f'    or run: {HERE}/install.sh --udev                              # permanent')
    return None


def main():
    ap = argparse.ArgumentParser(description='Use phones as Xbox controllers on Linux.')
    ap.add_argument('--port', type=int, default=8777)
    ap.add_argument('--players', type=int, default=4, help='max phone controllers (default 4)')
    ap.add_argument('--code', help='fixed join code (default: random, saved in ~/.config/deckpad/code)')
    ap.add_argument('--fake', action='store_true', help='no real controllers; for testing without /dev/uinput')
    args = ap.parse_args()

    if not args.fake:
        problem = check_uinput()
        if problem:
            print('deckpad:', problem, file=sys.stderr)
            sys.exit(1)

    with open(os.path.join(HERE, 'pad.html'), 'rb') as f:
        page = f.read()
    srv = ThreadingHTTPServer(('0.0.0.0', args.port), Handler)
    srv.daemon_threads = True
    srv.page = page
    srv.code = load_code(args.code)
    srv.pool = Pool(args.players, args.fake)
    print(f'deckpad ready{" (fake controllers)" if args.fake else ""}. On each phone, open:')
    for a in lan_addresses() or ['<this machine\'s IP>']:
        print(f'    http://{a}:{args.port}')
    print(f'and enter code {srv.code}', flush=True)
    try:
        srv.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        srv.pool.close()


if __name__ == '__main__':
    main()
