#!/usr/bin/env python3
import os, sys, time, select, termios, struct, zlib

PORT = "/dev/ttyUSB1"
BIN = sys.argv[1]
SLOT = int(sys.argv[2], 0)
FORCE = int(sys.argv[3])
VERSION = int(sys.argv[4], 0)
LOG = sys.argv[5] if len(sys.argv) > 5 else "/tmp/ep09_loader.log"

fd = os.open(PORT, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
a = termios.tcgetattr(fd)
a[0] = 0; a[1] = 0
a[2] = termios.CLOCAL | termios.CREAD | termios.CS8
a[3] = 0; a[4] = termios.B115200; a[5] = termios.B115200
a[6][termios.VMIN] = 0; a[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSANOW, a)

log = bytearray()
def note(s):
    log.extend(s.encode() if isinstance(s, str) else s)
    print(s, end="", flush=True)

def read_some(t=0.05):
    r, _, _ = select.select([fd], [], [], t)
    if not r:
        return b""
    try:
        b = os.read(fd, 4096)
    except OSError:
        return b""
    if b:
        log.extend(b)
        print(b.decode(errors="replace"), end="", flush=True)
    return b

def wait_for(token, timeout):
    buf = bytearray()
    end = time.time() + timeout
    while time.time() < end:
        b = read_some()
        if b:
            buf.extend(b)
            if token in buf:
                return True
    return False

def wait_for_any(tokens, timeout):
    buf = bytearray()
    end = time.time() + timeout
    while time.time() < end:
        b = read_some()
        if b:
            buf.extend(b)
            for token in tokens:
                if token in buf:
                    return token
    return None

note("WAIT_FRESH_BOOT\n")
if not wait_for(b"EP09 FLASH BOOTLOADER", 70):
    note("NO_BOOTLOADER_BANNER\n"); sys.exit(1)
if wait_for(b"PRESS L", 12):
    note("SENT_L\n")
    os.write(fd, b"L")
    if not wait_for(b"LOADER READY", 6):
        note("NO_LOADER_READY\n"); sys.exit(1)
elif wait_for(b"LOADER READY", 2):
    note("LOADER_ALREADY_READY\n")
else:
    note("NO_BOOTLOADER_PROMPT\n"); sys.exit(1)

data = open(BIN, "rb").read()
crc = zlib.crc32(data) & 0xffffffff
if FORCE:
    # Keep the payload valid, but advertise a wrong CRC.  The bootloader
    # force path then writes a good image with bad metadata, which is the
    # only way to exercise the later CRC-failure fallback.
    crc ^= 0xffffffff
hdr = b"P" + bytes([SLOT, FORCE]) + struct.pack("<III", len(data), crc, VERSION)
note("FRAME slot=%d force=%d len=%d crc=%08x ver=%08x\n" % (SLOT, FORCE, len(data), crc, VERSION))
os.write(fd, hdr)
time.sleep(0.002)
for i in range(0, len(data), 32):
    os.write(fd, data[i:i+32])
    time.sleep(0.003)

if not wait_for(b"EP09 APP", 20):
    note("NO_APP_SWITCH\n"); sys.exit(1)
end = time.time() + 3.0
while time.time() < end:
    read_some(0.1)
open(LOG, "wb").write(log)
note("LOADER_DONE\n")
