#!/usr/bin/env python3
"""Tokibot card updater: puts a new image on a gotchi's SD card and keeps its progress.

    curl -fsSL https://tokibot.lottes.dev/update-card.sh | bash

or download this file and run `python3 update-card.py` (it asks for sudo itself).
It finds the card, lets you pick a version, backs up the settings (tokibot.toml),
the progress partition (/data: XP, friends, keys) and the start of the card, writes
the image and puts /data and tokibot.toml back. Nothing is written before you
confirm. macOS and Linux, Python 3.8+ standard library only.
"""
import argparse
import gzip
import hashlib
import json
import lzma
import os
import plistlib
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time
import urllib.request

REPO = os.environ.get("TOKIBOT_REPO", "a-lottes/tokibot")
SITE = os.environ.get("TOKIBOT_SITE", "https://tokibot.lottes.dev")
MAX_BYTES = 128 * 1000 ** 3        # anything bigger is not an SD card
CHUNK = 4 << 20
SECTOR = 512
BOARDS = {"zerow": "Pi Zero W", "zero2w": "Pi Zero 2 W"}

# --- critters: generated by app/tools/tui_critters.py, do not edit ---
CRITTERS = {
    'ready': [
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠀⠀⢀⡀⠀', '⠀⠀⢀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⣀⣸⡇⠀', '⠀⠀⢸⡇⠀⢠⣶⡄⠀⠀⠀⠀⠀⢠⣶⡄⠀⢸⡿⠏⠁⠀', '⢰⣶⣾⡇⠀⠘⠿⠃⠀⠀⠀⠀⠀⠘⠿⠃⠀⢸⡇⠀⠀⠀', '⠈⠹⠿⢇⡀⠀⠀⠀⠀⠠⣀⠄⠀⠀⠀⠀⢀⡸⠇⠀⠀⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡶⠶⢶⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠀⠀⠀'],
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠀⠀⢀⡀⠀', '⠀⠀⢀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⣀⣸⡇⠀', '⠀⠀⢸⡇⠀⢠⣶⡄⠀⠀⠀⠀⠀⢠⣶⡄⠀⢸⡿⠏⠁⠀', '⢰⣶⣾⡇⠀⠘⠿⠃⠀⠀⠀⠀⠀⠘⠿⠃⠀⢸⡇⠀⠀⠀', '⠈⠹⠿⢇⡀⠀⠀⠀⠀⠠⣀⠄⠀⠀⠀⠀⢀⡸⠇⠀⠀⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡶⠶⢶⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠀⠀⠀'],
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠀⠀⢀⡀⠀', '⠀⠀⢀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⣀⣸⡇⠀', '⠀⠀⢸⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡿⠏⠁⠀', '⢰⣶⣾⡇⠀⠈⠒⠁⠀⠀⠀⠀⠀⠈⠒⠁⠀⢸⡇⠀⠀⠀', '⠈⠹⠿⢇⡀⠀⠀⠀⠀⠠⣀⠄⠀⠀⠀⠀⢀⡸⠇⠀⠀⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡶⠶⢶⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠀⠀⠀'],
    ],
    'waiting': [
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠔⢒⠄⠀', '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠅⠀⠀', '⠀⠀⠀⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠀⠀⠀⠀⠀', '⠀⠀⢀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⡀⠀⠀⠀', '⠀⠀⢸⡇⠀⢰⣦⠀⠀⠀⠀⠀⠀⢰⣦⠀⠀⢸⡇⠀⠀⠀', '⢰⣶⣾⡇⠀⠸⠟⠀⠀⠀⠀⠀⠀⠸⠟⠀⠀⢸⣷⣶⡆⠀', '⠈⠹⠿⢇⡀⠀⠀⠀⠀⠠⠤⠄⠀⠀⠀⠀⢀⡸⠿⠏⠁⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡶⠶⢶⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠀⠀⠀'],
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠐⢉⠕⠀', '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠐⠀⠀', '⠀⠀⠀⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠀⠀⠀⠀⠀', '⠀⠀⢀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⡀⠀⠀⠀', '⠀⠀⢸⡇⠀⠀⣴⡆⠀⠀⠀⠀⠀⠀⣴⡆⠀⢸⡇⠀⠀⠀', '⢰⣶⣾⡇⠀⠀⠻⠇⠀⠀⠀⠀⠀⠀⠻⠇⠀⢸⣷⣶⡆⠀', '⠈⠹⠿⢇⡀⠀⠀⠀⠀⠠⠤⠄⠀⠀⠀⠀⢀⡸⠿⠏⠁⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡶⠶⢶⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠀⠀⠀'],
    ],
    'permission': [
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣤⠀⠀', '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣛⠀⠀', '⢀⡀⠀⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠀⠀⢀⡀⠀', '⢸⣇⣀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⣀⣸⡇⠀', '⠈⠹⢿⡇⠀⢰⢒⡆⠀⠀⠀⠀⠀⢰⢒⡆⠀⢸⡿⠏⠁⠀', '⠀⠀⢸⡇⠀⠸⠬⠇⠀⠀⠀⠀⠀⠸⠬⠇⠀⢸⡇⠀⠀⠀', '⠀⠀⠸⢇⡀⠀⠀⠀⠀⢠⠒⡄⠀⠀⠀⠀⢀⡸⠇⠀⠀⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡶⠿⢶⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠀⠀⠀'],
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⠀⠀', '⠀⠀⠀⠀⠀⠀⢀⣀⣀⣀⣀⣀⣀⣀⡀⠀⠀⠀⠀⠒⠀⠀', '⢰⡆⠀⢀⡰⠶⠎⠉⠉⠉⠉⠉⠉⠉⠱⠶⢆⡀⠀⢰⡆⠀', '⠸⢷⣶⡎⠁⢀⣀⡀⠀⠀⠀⠀⠀⢀⣀⡀⠈⢱⣶⡾⠇⠀', '⠀⠈⢹⡇⠀⢸⠰⡇⠀⠀⠀⠀⠀⢸⠰⡇⠀⢸⡏⠁⠀⠀', '⠀⠀⢸⡇⠀⠈⠉⠁⠀⠀⣀⠀⠀⠈⠉⠁⠀⢸⡇⠀⠀⠀', '⠀⠀⠈⠱⢆⣀⣀⣀⣀⣘⣤⣃⣀⣀⣀⣀⡰⠎⠁⠀⠀⠀', '⠀⠀⠀⢰⣾⡏⠉⢹⣿⡏⠉⢹⣿⡏⠉⢹⣷⡆⠀⠀⠀⠀', '⠀⠀⠀⠈⠉⠁⠀⠈⠉⠁⠀⠈⠉⠁⠀⠈⠉⠁⠀⠀⠀⠀'],
    ],
    'working': [
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⠀⠀⠀⠀⠶⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠀⠀⠀⠀⠀', '⠀⠀⢀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⡀⠀⠀⠀', '⢀⣀⣸⡇⠀⠠⠤⠄⠀⠀⠀⠀⠀⠠⠤⠄⠀⢸⣇⣀⡀⠀', '⠸⠿⢿⡇⠀⠘⠿⠃⠀⠀⠀⠀⠀⠘⠿⠃⠀⢸⡿⠿⠇⠀', '⠀⠀⠸⢇⡀⠀⠀⠀⠀⠀⠤⠀⠀⠀⠀⠀⢀⡸⠇⠀⠀⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡶⠶⢶⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠸⠿⠇⠀⠈⠉⠁⠀⠸⠿⠇⠀⠈⠉⠁⠀⠀⠀⠀'],
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⠀⠀⠀⠀⠶⠀⠶⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠀⠀⠀⠀⠀', '⠀⠀⢀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⡀⠀⠀⠀', '⢀⣀⣸⡇⠀⠠⠤⠄⠀⠀⠀⠀⠀⠠⠤⠄⠀⢸⣇⣀⡀⠀', '⠸⠿⢿⡇⠀⠘⠿⠃⠀⠀⠀⠀⠀⠘⠿⠃⠀⢸⡿⠿⠇⠀', '⠀⠀⠸⢇⡀⠀⠀⠀⠀⠀⠤⠀⠀⠀⠀⠀⢀⡸⠇⠀⠀⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡶⠶⢶⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠈⠉⠁⠀⠸⠿⠇⠀⠈⠉⠁⠀⠸⠿⠇⠀⠀⠀⠀'],
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⠀⠀⠀⠀⠶⠀⠶⠀⠶⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠀⠀⠀⠀⠀', '⠀⠀⢀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⡀⠀⠀⠀', '⢀⣀⣸⡇⠀⠠⠤⠄⠀⠀⠀⠀⠀⠠⠤⠄⠀⢸⣇⣀⡀⠀', '⠸⠿⢿⡇⠀⠘⠿⠃⠀⠀⠀⠀⠀⠘⠿⠃⠀⢸⡿⠿⠇⠀', '⠀⠀⠸⢇⡀⠀⠀⠀⠀⠀⠤⠀⠀⠀⠀⠀⢀⡸⠇⠀⠀⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡶⠶⢶⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠸⠿⠇⠀⠈⠉⠁⠀⠸⠿⠇⠀⠈⠉⠁⠀⠀⠀⠀'],
    ],
    'hungry': [
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠀⠢⠀⠀⠀', '⠀⠀⢀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⡀⠀⠀⠀', '⢀⣀⣸⡇⠀⢀⣀⡀⠀⠀⠀⠀⠀⢀⣀⡀⠀⢸⡇⠀⠀⠀', '⠸⠿⢿⡇⠀⠈⠛⠁⠀⠀⠀⠀⠀⠈⠛⠁⠀⢸⣷⣶⡆⠀', '⠀⠀⠸⢇⡀⠀⠀⠀⠀⢠⠒⡄⠀⠀⠀⠀⢀⡸⠿⠏⠁⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡶⠿⢶⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠀⠀⠀'],
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠀⢀⠀⠀⠀', '⠀⠀⢀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⡀⠁⠀⠀', '⢀⣀⣸⡇⠀⢰⣦⠀⠀⠀⠀⠀⠀⢰⣦⠀⠀⢸⡇⠀⠀⠀', '⠸⠿⢿⡇⠀⠸⠟⠀⠀⠀⠀⠀⠀⠸⠟⠀⠀⢸⣷⣶⡆⠀', '⠀⠀⠸⢇⡀⠀⠀⠀⠀⢠⠒⡄⠀⠀⠀⠀⢀⡸⠿⠏⠁⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡶⠿⢶⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠀⠀⠀'],
    ],
    'flow': [
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠠⢜⠤⠀', '⠀⠀⠀⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠀⠀⠈⠀⠀', '⠀⠀⢀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⡀⠀⠀⠀', '⢀⣀⣸⡇⠀⠠⠤⠄⠀⠀⠀⠀⠀⠠⠤⠄⠀⢸⣇⣀⡀⠀', '⠸⠿⢿⡇⠀⠘⠿⠃⠀⠀⠀⠀⠀⠘⠿⠃⠀⢸⡿⠿⠇⠀', '⠀⠀⠸⢇⡀⠀⠀⠀⠠⡀⠀⢀⠄⠀⠀⠀⢀⡸⠇⠀⠀⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡾⠿⢷⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠸⠿⠇⠀⠈⠉⠁⠀⠸⠿⠇⠀⠈⠉⠁⠀⠀⠀⠀'],
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡀⠀⠀', '⠀⠀⠀⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠀⠒⡕⠂⠀', '⠀⠀⢀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⡀⠀⠀⠀', '⢀⣀⣸⡇⠀⢀⠤⡀⠀⠀⠀⠀⠀⢀⠤⡀⠀⢸⣇⣀⡀⠀', '⠸⠿⢿⡇⠀⠈⠀⠁⠀⠀⠀⠀⠀⠈⠀⠁⠀⢸⡿⠿⠇⠀', '⠀⠀⠸⢇⡀⠀⠀⠀⠠⡀⠀⢀⠄⠀⠀⠀⢀⡸⠇⠀⠀⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡾⠿⢷⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠈⠉⠁⠀⠸⠿⠇⠀⠈⠉⠁⠀⠸⠿⠇⠀⠀⠀⠀'],
    ],
    'relieved': [
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠠⢜⠤⠀', '⠀⠀⠀⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠀⠀⠈⠀⠀', '⠀⠀⢀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⡀⠀⠀⠀', '⠀⠀⢸⡇⠀⢀⠤⡀⠀⠀⠀⠀⠀⢀⠤⡀⠀⢸⡇⠀⠀⠀', '⢰⣶⣾⡇⠀⠈⠀⠁⠀⠀⠀⠀⠀⠈⠀⠁⠀⢸⣷⣶⡆⠀', '⠈⠹⠿⢇⡀⠀⠀⠀⠠⡀⠀⢀⠄⠀⠀⠀⢀⡸⠿⠏⠁⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡾⠿⢷⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠀⠀⠀'],
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠀⠀⠀', '⠀⠀⠀⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠐⢪⠒⠀⠀', '⠀⠀⢀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⡀⠀⠀⠀', '⠀⠀⢸⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡇⠀⠀⠀', '⢰⣶⣾⡇⠀⠈⠒⠁⠀⠀⠀⠀⠀⠈⠒⠁⠀⢸⣷⣶⡆⠀', '⠈⠹⠿⢇⡀⠀⠀⠀⠠⡀⠀⢀⠄⠀⠀⠀⢀⡸⠿⠏⠁⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡾⠿⢷⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠀⠀⠀'],
    ],
    'done': [
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠤⡣⠄', '⢉⡎⠁⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠀⠀⢀⡁⠀', '⢸⣇⣀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⣀⣸⡇⠀', '⠈⠹⢿⡇⠀⢀⠤⡀⠀⠀⠀⠀⠀⢀⠤⡀⠀⢸⡿⠏⠁⠀', '⠀⠀⢸⡇⠀⠈⠀⠁⠀⠀⠀⠀⠀⠈⠀⠁⠀⢸⡇⠀⠀⠀', '⠀⠀⠸⢇⡀⠀⠀⠀⠰⡒⠒⢒⠆⠀⠀⠀⢀⡸⠇⠀⠀⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡾⠿⢷⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠀⠀⠀'],
        ['⠀⠀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠒⡕⠂⠀⠀⢀⣀⣀⣀⣀⣀⣀⣀⡀⠀⠀⠀⠀⡀⠀⠀', '⢰⡆⠀⢀⡰⠶⠎⠉⠉⠉⠉⠉⠉⠉⠱⠶⢆⡀⠒⣵⡆⠀', '⠸⢷⣶⡎⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⢱⣶⡾⠇⠀', '⠀⠈⢹⡇⠀⠰⠉⠆⠀⠀⠀⠀⠀⠰⠉⠆⠀⢸⡏⠁⠀⠀', '⠀⠀⢸⡇⠀⠀⠀⠀⢀⣀⣀⣀⡀⠀⠀⠀⠀⢸⡇⠀⠀⠀', '⠀⠀⠈⠱⢆⣀⣀⣀⣈⣢⣤⣔⣁⣀⣀⣀⡰⠎⠁⠀⠀⠀', '⠀⠀⠀⢰⣾⡏⠉⢹⣿⡏⠉⢹⣿⡏⠉⢹⣷⡆⠀⠀⠀⠀', '⠀⠀⠀⠈⠉⠁⠀⠈⠉⠁⠀⠈⠉⠁⠀⠈⠉⠁⠀⠀⠀⠀'],
    ],
    'error': [
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢴⡯⠀⠀', '⠀⠀⠀⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠀⠉⠀⠀⠀', '⠀⠀⢀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⡀⠀⠀⠀', '⠀⠀⢸⡇⠀⠠⣀⠄⠀⠀⠀⠀⠀⠠⣀⠄⠀⢸⡇⠀⠀⠀', '⢰⣶⣾⡇⠀⠐⠉⠂⠀⠀⠀⠀⠀⠐⠉⠂⠀⢸⣷⣶⡆⠀', '⠈⠹⠿⢇⡀⠀⠀⠀⢀⠤⣀⠤⡀⠀⠀⠀⢀⡸⠿⠏⠁⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡶⠶⢶⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠀⠀⠀'],
        ['⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⠄⠀', '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠨⠟⠁⠀', '⠀⠀⠀⠀⢀⣀⡰⠶⠶⠶⠶⠶⠶⠶⢆⣀⡀⠀⠀⠀⠀⠀', '⠀⠀⢀⡰⠎⠉⠁⠀⠀⠀⠀⠀⠀⠀⠈⠉⠱⢆⡀⠀⠀⠀', '⠀⠀⢸⡇⠀⠠⣀⠄⠀⠀⠀⠀⠀⠠⣀⠄⠀⢸⡇⠀⠀⠀', '⢰⣶⣾⡇⠀⠐⠉⠂⠀⠀⠀⠀⠀⠐⠉⠂⠀⢸⣷⣶⡆⠀', '⠈⠹⠿⢇⡀⠀⠀⠀⢀⠤⣀⠤⡀⠀⠀⠀⢀⡸⠿⠏⠁⠀', '⠀⠀⠀⢈⣱⡶⠶⢶⣶⡶⠶⢶⣶⡶⠶⢶⣎⡁⠀⠀⠀⠀', '⠀⠀⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠸⠿⠇⠀⠀⠀⠀'],
    ],
}
# --- end of critters ---


# --- terminal ----------------------------------------------------------------------------

ACCENT, DIM, BOLD, GREEN, RED, RESET = ("\033[38;5;173m", "\033[2m", "\033[1m",
                                        "\033[32m", "\033[31m", "\033[0m")
SPINNER = "·✢✳∗✻✽✻∗✳✢"
WIDTH = 74


def visible(s):
    return len(re.sub(r"\033\[[0-9;]*m", "", s))


def pad(s, width):
    return s + " " * max(0, width - visible(s))


class Screen:
    """Redraws the whole UI in place: a box with the critter and facts, then a body."""

    def __init__(self, tty):
        self.tty = tty
        self.mood, self.facts, self.body, self.help = "ready", [], [], ""
        self.lock = threading.Lock()
        self.tick = 0

    def write(self, s):
        self.tty.write(s)
        self.tty.flush()

    def draw(self):
        with self.lock:
            frames = CRITTERS.get(self.mood) or CRITTERS.get("ready") or [[]]
            art = frames[(self.tick // 4) % len(frames)]
            inner = WIDTH - 2
            out = ["\033[H", ACCENT + "╭" + "─" * inner + "╮" + RESET]
            title = f" {ACCENT}✻{RESET} {BOLD}Tokibot card updater{RESET}"
            out.append(ACCENT + "│" + RESET + pad(title, inner) + ACCENT + "│" + RESET)
            rows = max(len(art), len(self.facts))
            for i in range(rows):
                left = art[i] if i < len(art) else " " * 22
                fact = self.facts[i] if i < len(self.facts) else ""
                if fact:
                    label, value = fact
                    fact = f"{DIM}{label:<9}{RESET}{value}"
                line = f" {ACCENT}{left}{RESET}  {fact}"
                out.append(ACCENT + "│" + RESET + pad(line, inner) + ACCENT + "│" + RESET)
            out.append(ACCENT + "╰" + "─" * inner + "╯" + RESET)
            out.append("")
            out += self.body
            out.append("")
            out.append(f"  {DIM}{self.help}{RESET}")
            self.write("\033[K\n".join(out) + "\033[K\033[J")

    def spin(self):
        return ACCENT + SPINNER[self.tick % len(SPINNER)] + RESET


def read_key(tty):
    ch = os.read(tty.fileno(), 1)
    if ch == b"\x1b":
        seq = os.read(tty.fileno(), 2)
        return {b"[A": "up", b"[B": "down"}.get(seq, "esc")
    if ch in (b"\r", b"\n"):
        return "enter"
    if ch in (b"k",):
        return "up"
    if ch in (b"j",):
        return "down"
    if ch in (b"q", b"\x03"):
        return "esc"
    return ""


def menu(screen, question, options, mood="waiting"):
    """options: [(label, detail)]. Returns the chosen index or None (esc)."""
    sel = 0
    screen.mood, screen.help = mood, "↑/↓ to select · enter to confirm · esc to cancel"
    while True:
        body = [f"  {BOLD}{question}{RESET}", ""]
        for i, (label, detail) in enumerate(options):
            mark = f"{ACCENT}❯{RESET}" if i == sel else " "
            text = f"{ACCENT}{label}{RESET}" if i == sel else label
            body.append(f"  {mark} {i + 1}. {text}" + (f"  {DIM}{detail}{RESET}" if detail else ""))
        screen.body = body
        screen.draw()
        key = read_key(screen.tty)
        if key == "up":
            sel = (sel - 1) % len(options)
        elif key == "down":
            sel = (sel + 1) % len(options)
        elif key == "enter":
            return sel
        elif key == "esc":
            return None


class Steps:
    """The list of steps below the box, Claude Code style: ⏺ title, ⎿ detail."""

    def __init__(self, screen, titles):
        self.screen, self.titles = screen, titles
        self.state = ["todo"] * len(titles)
        self.detail = [""] * len(titles)
        self.stop = threading.Event()
        self.thread = threading.Thread(target=self._animate, daemon=True)
        self.thread.start()

    def _animate(self):
        while not self.stop.wait(0.12):
            self.screen.tick += 1
            self.render()

    def render(self):
        body = []
        for i, title in enumerate(self.titles):
            st = self.state[i]
            dot = {"todo": f"{DIM}○{RESET}", "run": self.screen.spin(),
                   "ok": f"{GREEN}⏺{RESET}", "fail": f"{RED}⏺{RESET}"}[st]
            text = title if st != "todo" else f"{DIM}{title}{RESET}"
            body.append(f"  {dot} {text}")
            if self.detail[i] and st != "todo":
                body.append(f"    {DIM}⎿  {self.detail[i]}{RESET}")
        self.screen.body = body
        self.screen.draw()

    def run(self, i, mood, detail=""):
        self.state[i], self.detail[i], self.screen.mood = "run", detail, mood

    def note(self, i, detail):
        self.detail[i] = detail

    def ok(self, i, detail=None):
        self.state[i] = "ok"
        if detail is not None:
            self.detail[i] = detail

    def fail(self, i, detail):
        self.state[i], self.detail[i], self.screen.mood = "fail", detail, "error"

    def close(self):
        self.stop.set()
        self.thread.join()
        self.render()


def bar(done, total, width=24):
    frac = 0 if not total else min(1, done / total)
    full = int(frac * width)
    return f"{'█' * full}{'░' * (width - full)} {frac * 100:3.0f}%"


def human(n):
    for unit in ("B", "KB", "MB", "GB"):
        if n < 1000 or unit == "GB":
            return f"{n:.0f} {unit}" if unit in ("B", "KB") else f"{n:.1f} {unit}"
        n /= 1000


# --- the card ------------------------------------------------------------------------------

def run(*cmd, check=True):
    return subprocess.run(cmd, capture_output=True, text=True, check=check).stdout


class Mac:
    def disks(self):
        info = plistlib.loads(run("diskutil", "list", "-plist", "physical").encode())
        found = []
        for entry in info.get("AllDisksAndPartitions", []):
            name = entry["DeviceIdentifier"]
            d = plistlib.loads(run("diskutil", "info", "-plist", name).encode())
            if d.get("Internal", True) and not d.get("RemovableMedia") and not d.get("Removable"):
                continue
            labels = [p.get("VolumeName", "") for p in entry.get("Partitions", [])]
            found.append({"name": name, "size": entry.get("Size", 0), "labels": labels,
                          "model": d.get("MediaName", "")})
        return found

    def raw(self, disk):
        return f"/dev/r{disk}"

    def boot_part(self, disk):
        return f"{disk}s1"

    def unmount(self, disk):
        run("diskutil", "unmountDisk", f"/dev/{disk}", check=False)

    def settle(self, disk):
        time.sleep(3)                  # macOS mounts the new boot partition right away
        self.unmount(disk)

    def mount_boot(self, disk):
        run("diskutil", "mount", self.boot_part(disk))
        d = plistlib.loads(run("diskutil", "info", "-plist", self.boot_part(disk)).encode())
        return d.get("MountPoint")

    def umount_boot(self, mnt, disk):
        run("diskutil", "unmount", self.boot_part(disk), check=False)

    def eject(self, disk):
        run("diskutil", "eject", f"/dev/{disk}", check=False)


class Linux:
    def disks(self):
        data = json.loads(run("lsblk", "-J", "-b", "-o", "NAME,SIZE,RM,TRAN,TYPE,LABEL,MODEL"))
        found = []
        for d in data.get("blockdevices", []):
            if d.get("type") != "disk":
                continue
            removable = str(d.get("rm")) in ("1", "True", "true") or d.get("tran") == "usb" \
                or d["name"].startswith("mmcblk")
            if not removable:
                continue
            labels = [c.get("label") or "" for c in d.get("children", [])]
            found.append({"name": d["name"], "size": int(d.get("size") or 0), "labels": labels,
                          "model": (d.get("model") or "").strip()})
        return found

    def raw(self, disk):
        return f"/dev/{disk}"

    def boot_part(self, disk):
        return f"/dev/{disk}p1" if disk[-1].isdigit() else f"/dev/{disk}1"

    def unmount(self, disk):
        for line in run("lsblk", "-nro", "NAME,MOUNTPOINT", f"/dev/{disk}").splitlines():
            parts = line.split(maxsplit=1)
            if len(parts) == 2:
                run("umount", f"/dev/{parts[0]}", check=False)

    def settle(self, disk):
        run("blockdev", "--rereadpt", f"/dev/{disk}", check=False)
        time.sleep(2)
        self.unmount(disk)

    def mount_boot(self, disk):
        mnt = tempfile.mkdtemp(prefix="tokibot-boot-")
        run("mount", self.boot_part(disk), mnt)
        return mnt

    def umount_boot(self, mnt, disk):
        run("umount", mnt, check=False)
        os.rmdir(mnt)

    def eject(self, disk):
        run("sync", check=False)
        run("eject", f"/dev/{disk}", check=False)


def is_tokibot(disk):
    return any(label in ("TOKIBOT", "GOTCHI", "CLAUDEGOTCHI") for label in disk["labels"])


def partitions(mbr):
    """(start, sectors) of the four MBR entries."""
    return [(int.from_bytes(mbr[454 + 16 * i:458 + 16 * i], "little"),
             int.from_bytes(mbr[458 + 16 * i:462 + 16 * i], "little")) for i in range(4)]


def read_at(dev, offset, size):
    with open(dev, "rb", buffering=0) as f:
        f.seek(offset)
        out = bytearray()
        while len(out) < size:
            chunk = f.read(min(1 << 20, size - len(out)))
            if not chunk:
                break
            out += chunk
        return bytes(out)


def write_at(dev, offset, data):
    fd = os.open(dev, os.O_WRONLY)
    try:
        os.lseek(fd, offset, os.SEEK_SET)
        view = memoryview(data)
        while view:
            view = view[os.write(fd, view[:1 << 20]):]
        os.fsync(fd)
    finally:
        os.close(fd)


# --- releases ---------------------------------------------------------------------------

def fetch(url, timeout=30):
    req = urllib.request.Request(url, headers={"User-Agent": "tokibot-update-card"})
    return urllib.request.urlopen(req, timeout=timeout)


def releases(model):
    """[{tag, date, url, size, sha256, latest}] newest first, for this board."""
    names = (f"tokibot-{model}.img.xz", f"claudegotchi-{model}.img.xz")
    try:
        with fetch(f"https://api.github.com/repos/{REPO}/releases?per_page=30") as r:
            data = json.load(r)
    except Exception:
        data = []
    out = []
    for rel in data:
        if rel.get("draft") or rel.get("prerelease"):
            continue
        asset = next((a for a in rel.get("assets", []) if a["name"] in names), None)
        if asset:
            digest = asset.get("digest") or ""
            out.append({"tag": rel["tag_name"], "date": (rel.get("published_at") or "")[:10],
                        "url": asset["browser_download_url"], "size": asset.get("size", 0),
                        "sha256": digest.split(":", 1)[1] if digest.startswith("sha256:") else ""})
    if not out:                    # GitHub not reachable: the website has the newest one
        with fetch(f"{SITE}/downloads/latest.json") as r:
            latest = json.load(r)
        f = next(f for f in latest["files"] if f["name"] in names)
        out.append({"tag": latest["tag"], "date": latest.get("published", "")[:10],
                    "url": f"{SITE}/downloads/{f['name']}", "size": f["size"], "sha256": f["sha256"]})
    for i, rel in enumerate(out):
        rel["latest"] = i == 0
    return out


# --- the update -------------------------------------------------------------------------

class Failed(Exception):
    pass


def update(screen, plat, disk, rel, backup):
    steps = Steps(screen, ["Back up progress and settings", "Download the image",
                           "Check the image", "Write the card", "Put progress back",
                           "Put settings back"])
    try:
        raw = plat.raw(disk["name"])
        # 1. backup
        steps.run(0, "working", backup)
        os.makedirs(backup, exist_ok=True)
        plat.unmount(disk["name"])
        mbr = read_at(raw, 0, SECTOR)
        start, count = partitions(mbr)[2]
        if mbr[510:512] != b"\x55\xaa" or not count:
            raise Failed((0, "the card has no third partition (/data), is it a Tokibot card?"))
        data = read_at(raw, start * SECTOR, count * SECTOR)
        if len(data) != count * SECTOR:
            raise Failed((0, "could not read the /data partition"))
        with open(os.path.join(backup, "data.img"), "wb") as f:
            f.write(data)
        end = (start + count) * SECTOR
        with gzip.open(os.path.join(backup, "card-start.img.gz"), "wb", compresslevel=1) as f:
            with open(raw, "rb", buffering=0) as src:
                done = 0
                while done < end:
                    chunk = src.read(min(CHUNK, end - done))
                    if not chunk:
                        break
                    f.write(chunk)
                    done += len(chunk)
                    steps.note(0, f"whole card  {bar(done, end)}")
        toml = disk.get("toml")
        if toml is not None:
            with open(os.path.join(backup, "tokibot.toml"), "wb") as f:
                f.write(toml)
        steps.ok(0, f"data.img, card-start.img.gz{', tokibot.toml' if toml else ''} in {backup}")

        # 2. download
        steps.run(1, "hungry", rel["url"].rsplit("/", 1)[1])
        img = os.path.join(backup, rel["url"].rsplit("/", 1)[1])
        h = hashlib.sha256()
        with fetch(rel["url"], timeout=60) as r, open(img, "wb") as f:
            total = int(r.headers.get("Content-Length") or rel["size"] or 0)
            got = 0
            while True:
                chunk = r.read(1 << 20)
                if not chunk:
                    break
                f.write(chunk)
                h.update(chunk)
                got += len(chunk)
                steps.note(1, f"{bar(got, total)}  {human(got)}")
        steps.ok(1, f"{rel['tag']}, {human(got)}")

        # 3. checks
        steps.run(2, "flow")
        if rel["sha256"] and h.hexdigest() != rel["sha256"]:
            raise Failed((2, "the download is damaged (checksum differs), nothing written"))
        with lzma.open(img) as f:
            new_mbr = f.read(SECTOR)
        nstart, ncount = partitions(new_mbr)[2]
        if (nstart, ncount) != (start, count):
            raise Failed((2, f"the new image puts /data elsewhere ({nstart}+{ncount}, card has "
                             f"{start}+{count}); nothing written, flash it with Imager instead"))
        steps.ok(2, "checksum and partition layout fit" if rel["sha256"] else "partition layout fits")

        # 4. write
        steps.run(3, "working")
        plat.unmount(disk["name"])
        size_in = os.path.getsize(img)
        fd = os.open(raw, os.O_WRONLY)
        try:
            dec = lzma.LZMADecompressor()
            pending = b""
            with open(img, "rb") as f:
                while True:
                    comp = f.read(1 << 20)
                    if comp:
                        pending += dec.decompress(comp)
                    if len(pending) >= CHUNK or (not comp and pending):
                        n = len(pending) if not comp else len(pending) // CHUNK * CHUNK
                        block = pending[:n]
                        if len(block) % SECTOR:
                            block += b"\0" * (SECTOR - len(block) % SECTOR)
                        view = memoryview(block)
                        while view:
                            view = view[os.write(fd, view):]
                        pending = pending[n:]
                    steps.note(3, bar(f.tell(), size_in))
                    if not comp:
                        break
            os.fsync(fd)
        finally:
            os.close(fd)
        os.remove(img)
        steps.ok(3, f"{rel['tag']} written")

        # 5. data back
        steps.run(4, "relieved")
        plat.settle(disk["name"])
        write_at(raw, start * SECTOR, data)
        if read_at(raw, start * SECTOR, count * SECTOR) != data:
            raise Failed((4, f"/data differs from the backup; it is safe in {backup}/data.img"))
        steps.ok(4, "XP, friends and keys checked byte for byte")

        # 6. settings back
        steps.run(5, "relieved")
        if toml is None:
            steps.ok(5, "there were none, the gotchi starts with the defaults")
        else:
            mnt = plat.mount_boot(disk["name"])
            try:
                with open(os.path.join(mnt, "tokibot.toml"), "wb") as f:
                    f.write(toml)
                    f.flush()
                    os.fsync(f.fileno())
                with open(os.path.join(mnt, "tokibot.toml"), "rb") as f:
                    if f.read() != toml:
                        raise Failed((5, "tokibot.toml was not copied back"))
            finally:
                plat.umount_boot(mnt, disk["name"])
            steps.ok(5, "tokibot.toml with your Wi-Fi and token")
        plat.eject(disk["name"])
        screen.mood = "done"
        return True
    except Failed as e:
        i, msg = e.args[0]
        steps.fail(i, msg)
        return False
    except Exception as e:  # noqa: BLE001 — show it instead of a traceback
        i = next((i for i, s in enumerate(steps.state) if s == "run"), 0)
        steps.fail(i, f"{type(e).__name__}: {e}")
        return False
    finally:
        steps.close()


def read_boot(plat, disk):
    """Board and settings from the card's FAT partition."""
    mnt = plat.mount_boot(disk["name"])
    try:
        with open(os.path.join(mnt, "config.txt")) as f:
            config = f.read()
        model = "zero2w" if re.search(r"^arm_64bit=1", config, re.M) else "zerow"
        toml = None
        for name in ("tokibot.toml", "claudegotchi.toml"):
            p = os.path.join(mnt, name)
            if os.path.exists(p):
                with open(p, "rb") as f:
                    toml = f.read()
                break
    finally:
        plat.umount_boot(mnt, disk["name"])
    ssid = ""
    if toml:
        m = re.search(rb'^\s*ssid\s*=\s*"([^"]*)"', toml, re.M)
        ssid = m.group(1).decode("utf-8", "replace") if m else ""
    return model, toml, ssid


def main():
    ap = argparse.ArgumentParser(description="Put a new Tokibot image on an SD card, keeping its progress.")
    ap.add_argument("--disk", help="the card (macOS: disk4, Linux: sdb or mmcblk0); asked when left out")
    args = ap.parse_args()

    if sys.platform not in ("darwin", "linux"):
        sys.exit("Only macOS and Linux are supported. On Windows, flash with Raspberry Pi Imager.")
    if os.geteuid() != 0:
        print("Writing an SD card needs administrator rights, so sudo asks for your password.")
        keep = [f"{k}={v}" for k, v in os.environ.items() if k.startswith("TOKIBOT_")]
        os.execvp("sudo", ["sudo", "env", *keep, sys.executable, os.path.abspath(__file__)] + sys.argv[1:])
    plat = Mac() if sys.platform == "darwin" else Linux()
    try:
        tty = open("/dev/tty", "r+", encoding="utf-8")
    except OSError:
        sys.exit("No terminal to talk to; run it in a terminal window.")

    import termios
    import tty as ttymod
    old = termios.tcgetattr(tty.fileno())
    screen = Screen(tty)

    def restore(*_):
        termios.tcsetattr(tty.fileno(), termios.TCSADRAIN, old)
        screen.write("\033[?25h\n")

    signal.signal(signal.SIGTERM, lambda *_: (restore(), sys.exit(1)))
    ttymod.setcbreak(tty.fileno())
    screen.write("\033[?25l\033[2J")
    code = 1
    try:
        code = session(screen, plat, args)
    except KeyboardInterrupt:
        screen.help = "stopped"
        screen.draw()
    finally:
        restore()
    sys.exit(code)


def wait_key(screen, text, mood):
    screen.mood, screen.help = mood, text
    screen.draw()
    return read_key(screen.tty)


def session(screen, plat, args):
    screen.facts = [("Card", "looking …")]
    screen.body = [f"  {screen.spin()} Looking for your gotchi's SD card …"]
    screen.help = ""
    screen.draw()

    # The card
    while True:
        disks = [d for d in plat.disks() if 0 < d["size"] <= MAX_BYTES]
        if args.disk:
            disks = [d for d in disks if d["name"] == args.disk.replace("/dev/", "").lstrip("r")]
        if disks:
            break
        screen.body = ["  No SD card found. Insert the gotchi's card (a card reader is fine)."]
        if wait_key(screen, "enter to look again · esc to quit", "waiting") == "esc":
            return 1
    disks.sort(key=lambda d: not is_tokibot(d))
    if len(disks) == 1 and is_tokibot(disks[0]):
        disk = disks[0]
    else:
        opts = [(f"{d['name']}  {human(d['size'])}",
                 ("Tokibot card" if is_tokibot(d) else d["model"] or "not a Tokibot card")) for d in disks]
        i = menu(screen, "Which card is the gotchi's?", opts)
        if i is None:
            return 1
        disk = disks[i]
    plat.unmount(disk["name"])
    try:
        model, toml, ssid = read_boot(plat, disk)
    except Exception:
        screen.body = [f"  {RED}{disk['name']} has no Tokibot boot partition.{RESET}",
                       "  For a new card, use Raspberry Pi Imager and the download page."]
        wait_key(screen, "any key to quit", "error")
        return 1
    disk["toml"] = toml
    screen.facts = [("Card", f"{disk['name']} · {human(disk['size'])}"),
                    ("Board", BOARDS[model]),
                    ("Wi-Fi", ssid or f"{DIM}none{RESET}"),
                    ("Settings", "tokibot.toml" if toml else f"{DIM}none{RESET}")]

    # The version
    screen.body = [f"  {screen.spin()} Looking up the versions …"]
    screen.draw()
    try:
        rels = releases(model)
    except Exception as e:
        screen.body = [f"  {RED}No versions found: {e}{RESET}", "  Are you online?"]
        wait_key(screen, "any key to quit", "error")
        return 1
    opts = [(r["tag"], f"{r['date']}{'  · newest' if r['latest'] else ''}") for r in rels]
    i = menu(screen, "Which version should the card get?", opts)
    if i is None:
        return 1
    rel = rels[i]
    screen.facts.append(("Version", f"{ACCENT}{rel['tag']}{RESET}"))

    # Confirm
    home = os.path.expanduser(f"~{os.environ.get('SUDO_USER', '')}")
    backup = os.path.join(home, f"tokibot-backup-{time.strftime('%Y-%m-%d-%H%M%S')}")
    screen.facts.append(("Backup", "~/" + os.path.basename(backup)))
    i = menu(screen, f"Erase {disk['name']} and put {rel['tag']} on it? Your progress is kept.",
             [("Yes, update the card", "backs up first"), ("No, stop", "")], mood="permission")
    if i != 0:
        return 1

    ok = update(screen, plat, disk, rel, backup)
    uid, gid = os.environ.get("SUDO_UID"), os.environ.get("SUDO_GID")
    if uid and os.path.isdir(backup):
        for root, dirs, files in os.walk(backup):
            for n in [root] + [os.path.join(root, f) for f in files]:
                try:
                    os.chown(n, int(uid), int(gid or uid))
                except OSError:
                    pass
    if ok:
        screen.body.append("")
        screen.body.append(f"  {GREEN}Done.{RESET} Put the card into the gotchi and switch it on.")
        wait_key(screen, "any key to quit", "done")
        return 0
    screen.body.append("")
    screen.body.append(f"  Nothing is lost: the backup is in {backup}.")
    wait_key(screen, "any key to quit", "error")
    return 1


if __name__ == "__main__":
    main()
