#!/usr/bin/env python3
"""
mk_nonmain.py - create, change and check NONMAIN images of the TI MSPM33

NONMAIN is the boot configuration of the MSPM33 (BCR and BSL configuration,
one 2 KB flash sector at 0x80101800). See README.md in this folder.

The script starts from an existing NONMAIN image (a binary file, e.g. from
"memory dump 0x80101800 0x800 tftp://server/nonmain.bin", or the text output
of "memory read32 0x80101800 512") or with --default from the built-in
factory default, changes fields, recomputes both CRC-32 and writes a new
binary image which PEEDI programs with
"flash program nonmain.bin bin 0x80101800" (needs "NONMAIN = YES" in the
flash section).

Examples:
  ./mk_nonmain.py nonmain_read.bin --info
  ./mk_nonmain.py --default -o nonmain_new.bin --set BOOTCFG1=0xAABB5522
  ./mk_nonmain.py nonmain_read.bin -o nonmain_new.bin --set BOOTCFG1=0xAABB5522
  ./mk_nonmain.py nonmain_read.bin -o nonmain_new.bin --set-ofs 0x434=0x10001000
  ./mk_nonmain.py --list

Copyright (c) Ronetix GmbH. All rights reserved.
"""

import argparse
import os
import struct
import sys

NONMAIN_BASE = 0x80101800
NONMAIN_SIZE = 0x800

BCR_START, BCR_CRC = 0x000, 0x14C       # BCR: 0x000..0x14B, CRC-32 at 0x14C
BSL_START, BSL_CRC = 0x400, 0x44C       # BSL: 0x400..0x44B, CRC-32 at 0x44C

ENABLED, DISABLED, ENABLED_PW = 0xAABB, 0x5522, 0xCCDD

# Field names and offsets in the sector (TRM SLAU962, 1.4.2 NON_MAIN registers)
FIELDS = [
    ("BCR_CONFIG_ID", 0x000, "BCR config signature ID (must match the device)"),
    ("BOOTCFG0", 0x004, "[31:16] SWDP_MODE, [15:0] DEBUG_ACCESS"),
    ("BOOTCFG1", 0x008, "[31:16] DEBUG_HOLD, [15:0] BSL_PIN_INVOKE"),
    ("BOOTCFG2", 0x00C, "CSC policy, flash bank swap policy"),
    ("BOOTCFG3", 0x010, "fast boot mode, bootloader mode"),
    ("BOOTCFG4", 0x014, "[31:16] FACTORY_RESET_MODE, [15:0] MASS_ERASE_MODE"),
] + [("MASS_ERASE_%d" % i, 0x018 + 4 * i, "mass erase password hash, word %d" % i) for i in range(8)] \
  + [("FACTORY_RESET_%d" % i, 0x038 + 4 * i, "factory reset password hash, word %d" % i) for i in range(8)] \
  + [("DEBUG_LOCK_%d" % i, 0x058 + 4 * i, "debug access password hash, word %d" % i) for i in range(8)] \
  + [("DEBUG_NS_LOCK_%d" % i, 0x078 + 4 * i, "non-secure debug password hash, word %d" % i) for i in range(8)] \
  + [("BAD_CONV_%d" % i, 0x098 + 4 * i, "bad conversion password hash, word %d" % i) for i in range(8)] \
  + [
    ("SECURE_BOOT_MODE", 0x0B8, "application authentication"),
    ("USER_SECURE_APP_START_ADDR", 0x0BC, "start address of the secure application"),
    ("USER_SECURE_APP_LENGTH", 0x0C0, "length of the secure application"),
] + [("USER_SECURE_APP_HASH_%d" % i, 0x0C4 + 4 * i, "secure application hash, word %d" % i) for i in range(8)] \
  + [
    ("BANK0_NM_USER_CONFIG", 0x0E4, "NONMAIN static write protection"),
    ("BANK0_WRITE_ERASE_PROTECTION_A", 0x0E8, "bank 0: write protection of the first 32 sectors"),
    ("BANK0_WRITE_ERASE_PROTECTION_B", 0x0EC, "bank 0: write protection 64KB..512KB"),
    ("BANK0_SECURITY_PROTECTION_A", 0x0F0, "bank 0: security protection of the first 32 sectors"),
    ("BANK0_SECURITY_PROTECTION_B", 0x0F4, "bank 0: security protection 64KB..512KB"),
    ("BANK0_PRIVILEGE_PROTECTION_A", 0x0F8, "bank 0: privilege protection of the first 32 sectors"),
    ("BANK0_PRIVILEGE_PROTECTION_B", 0x0FC, "bank 0: privilege protection 64KB..512KB"),
    ("BANK1_WRITE_ERASE_PROTECTION_A", 0x104, "bank 1: write protection of the first 32 sectors"),
    ("BANK1_WRITE_ERASE_PROTECTION_B", 0x108, "bank 1: write protection 64KB..512KB"),
    ("BANK1_SECURITY_PROTECTION_A", 0x10C, "bank 1: security protection of the first 32 sectors"),
    ("BANK1_SECURITY_PROTECTION_B", 0x110, "bank 1: security protection 64KB..512KB"),
    ("BANK1_PRIVILEGE_PROTECTION_A", 0x114, "bank 1: privilege protection of the first 32 sectors"),
    ("BANK1_PRIVILEGE_PROTECTION_B", 0x118, "bank 1: privilege protection 64KB..512KB"),
    ("DBANK_WRITE_ERASE_PROTECTION", 0x120, "DATA bank: write/erase protection"),
    ("DBANK_SECURITY_PROTECTION", 0x124, "DATA bank: security protection"),
    ("DBANK_PRIVILEGE_PROTECTION", 0x128, "DATA bank: privilege protection"),
    ("BOOTCLK0", 0x130, "boot clock configuration, PLL multiplier/divider"),
    ("BOOTCLK1", 0x134, "CPU delay cycles for the PLL settling time"),
    ("BCR_CRC", BCR_CRC, "CRC-32 of the BCR structure (computed by this script)"),
    ("BSL_CONFIG_ID", 0x400, "BSL config signature ID (must match the device)"),
    ("BSLPINCFG0", 0x404, "BSL UART pins"),
    ("BSLPINCFG1", 0x408, "BSL I2C pins"),
    ("BSLPINCFG2", 0x40C, "BSL MCAN pins"),
    ("BSLCONFIG0", 0x410, "BSL invoke pin configuration"),
] + [("PASSWORD_%d" % i, 0x414 + 4 * i, "BSL access password, word %d" % i) for i in range(8)] \
  + [
    ("APP_REV_POINTER", 0x434, "pointer to the application version in MAIN flash"),
    ("BSLCONFIG1", 0x438, "BSL security alert response, UART speed"),
    ("I2C_SLAVE_ADDR", 0x43C, "BSL I2C slave address"),
    ("BSL_CRC", BSL_CRC, "CRC-32 of the BSL structure (computed by this script)"),
]
FIELD_BY_NAME = {f[0]: f for f in FIELDS}

# Factory default of the MSPM33C321A (read after a DSSM factory reset,
# 2026-12-03): offset -> value of the words which are not 0xFFFFFFFF.
# Another device revision may have other defaults or config IDs - reading
# the NONMAIN of the device is safer.
DEFAULT_WORDS = {
    0x000: 0x05000000,  # BCR_CONFIG_ID
    0x004: 0xAABBAABB,  # BOOTCFG0: SWD enabled, debug access enabled
    0x008: 0xAABBAABB,  # BOOTCFG1
    0x00C: 0xAABBAABB,  # BOOTCFG2
    0x010: 0xAABBFFFF,  # BOOTCFG3
    0x014: 0xAABBAABB,  # BOOTCFG4: factory reset enabled, mass erase enabled
    0x0E4: 0xFFFFAABB,  # BANK0_NM_USER_CONFIG
    0x0F0: 0x00000000,  # BANK0_SECURITY_PROTECTION_A
    0x0F4: 0x00000000,  # BANK0_SECURITY_PROTECTION_B
    0x0F8: 0x00000000,  # BANK0_PRIVILEGE_PROTECTION_A
    0x0FC: 0x00000000,  # BANK0_PRIVILEGE_PROTECTION_B
    0x10C: 0x00000000,  # BANK1_SECURITY_PROTECTION_A
    0x110: 0x00000000,  # BANK1_SECURITY_PROTECTION_B
    0x114: 0x00000000,  # BANK1_PRIVILEGE_PROTECTION_A
    0x118: 0x00000000,  # BANK1_PRIVILEGE_PROTECTION_B
    0x124: 0x00000000,  # DBANK_SECURITY_PROTECTION
    0x128: 0x00000000,  # DBANK_PRIVILEGE_PROTECTION
    0x130: 0xFF000FFF,  # BOOTCLK0
    0x134: 0xFFFF08C8,  # BOOTCLK1
    0x14C: 0x7B106534,  # BCR CRC
    0x400: 0x05000000,  # BSL_CONFIG_ID
    0x404: 0x07150716,  # BSLPINCFG0
    0x408: 0x06020601,  # BSLPINCFG1
    0x40C: 0x043B043C,  # BSLPINCFG2
    0x410: 0xAABB12A8,  # BSLCONFIG0
    0x414: 0x761396AF,  # PASSWORD_0..7
    0x418: 0x5F63720F,
    0x41C: 0x5A4AB4BD,
    0x420: 0x9FC3630A,
    0x424: 0xF930AF12,
    0x428: 0x5CEEA650,
    0x42C: 0x88E11B97,
    0x430: 0x51409CE8,
    0x438: 0x0002FFFF,  # BSLCONFIG1
    0x43C: 0xFFFF0048,  # I2C_SLAVE_ADDR
    0x44C: 0xAF559B73,  # BSL CRC
}


def crc32_nonmain(data):
    """CRC-32 as the MSPM33 boot code: polynomial 0xEDB88320 (reflected),
    initial value 0xFFFFFFFF, no final XOR."""
    crc = 0xFFFFFFFF
    for b in data:
        crc ^= b
        for _ in range(8):
            crc = (crc >> 1) ^ 0xEDB88320 if crc & 1 else crc >> 1
    return crc


def get32(img, ofs):
    return struct.unpack_from("<I", img, ofs)[0]


def put32(img, ofs, val):
    struct.pack_into("<I", img, ofs, val & 0xFFFFFFFF)


def default_image():
    img = bytearray(b"\xFF" * NONMAIN_SIZE)
    for ofs, val in DEFAULT_WORDS.items():
        struct.pack_into("<I", img, ofs, val)
    return img


def read_image(path):
    """Binary image (2048 bytes) or the text of "memory read32 0x80101800 512"."""
    try:
        with open(path, "rb") as f:
            raw = f.read()
    except OSError as e:
        fatal("%s: %s\n  read the NONMAIN of the device first (README.md, step 1), "
              "or start from the factory default with --default" % (path, e.strerror))
    if len(raw) == NONMAIN_SIZE and not raw.lstrip().startswith(b"0x"):
        return bytearray(raw)

    words = {}
    for line in raw.decode("ascii", "replace").splitlines():
        line = line.strip()
        if ":" not in line or not line.lower().startswith("0x"):
            continue
        addr, rest = line.split(":", 1)
        try:
            addr = int(addr, 16)
            vals = [int(w, 16) for w in rest.split()]
        except ValueError:
            continue
        for i, v in enumerate(vals):
            words[addr + 4 * i] = v

    img = bytearray(NONMAIN_SIZE)
    for ofs in range(0, NONMAIN_SIZE, 4):
        if NONMAIN_BASE + ofs not in words:
            fatal("%s: address 0x%08X missing (not a binary image of %d bytes "
                  "and not a complete \"memory read32 0x80101800 512\" output)"
                  % (path, NONMAIN_BASE + ofs, NONMAIN_SIZE))
        put32(img, ofs, words[NONMAIN_BASE + ofs])
    return img


def update_crc(img):
    put32(img, BCR_CRC, crc32_nonmain(img[BCR_START:BCR_CRC]))
    put32(img, BSL_CRC, crc32_nonmain(img[BSL_START:BSL_CRC]))


# ---------------------------------------------------------------------------
# output
# ---------------------------------------------------------------------------

class Style:
    """ANSI colors and Unicode symbols, only on a terminal (NO_COLOR or
    --no-color switch the colors off; a non-UTF-8 terminal gets ASCII)."""

    def __init__(self, color):
        enc = (getattr(sys.stdout, "encoding", "") or "").lower()
        self.color = color
        self.utf8 = "utf" in enc
        u = self.utf8
        self.OK = "✔" if u else "+"
        self.ERR = "✘" if u else "x"
        self.WARN = "⚠" if u else "!"
        self.ARROW = "→" if u else "->"
        self.STAR = "★" if u else "*"
        self.DOT = "●" if u else "o"
        self.H, self.V = ("─", "│") if u else ("-", "|")
        self.TL, self.TR, self.BL, self.BR = ("╭", "╮", "╰", "╯") if u else ("+",) * 4

    def _c(self, code, text):
        return "\033[%sm%s\033[0m" % (code, text) if self.color else text

    def bold(self, t):   return self._c("1", t)
    def dim(self, t):    return self._c("2", t)
    def red(self, t):    return self._c("1;31", t)
    def green(self, t):  return self._c("32", t)
    def yellow(self, t): return self._c("33", t)
    def cyan(self, t):   return self._c("36", t)
    def title(self, t):  return self._c("1;36", t)


S = Style(False)


def visible_len(text):
    out, esc = 0, False
    for ch in text:
        if ch == "\033":
            esc = True
        elif esc:
            esc = ch != "m"
        else:
            out += 1
    return out


def box(lines, title=None):
    width = max([visible_len(l) for l in lines] + [len(title or "") + 2])
    if title:
        fill = width + 2 - (len(title) + 3)
        print(S.dim(S.TL + S.H) + " " + S.title(title) + " " + S.dim(S.H * fill + S.TR))
    else:
        print(S.dim(S.TL + S.H * (width + 2) + S.TR))
    for l in lines:
        print("%s %s%s %s" % (S.dim(S.V), l, " " * (width - visible_len(l)), S.dim(S.V)))
    print(S.dim(S.BL + S.H * (width + 2) + S.BR))


def section(title):
    print()
    print("%s %s" % (S.title(title), S.dim(S.H * max(2, 60 - len(title)))))


def ok(msg):    print("  %s %s" % (S.green(S.OK), msg))
def error(msg): print("  %s %s" % (S.red(S.ERR), S.red(msg)))
def warn(msg):  print("  %s %s" % (S.yellow(S.WARN), S.yellow(msg)))
def note(msg):  print("  %s" % S.dim(msg))


def fatal(msg):
    print("%s %s" % (S.red(S.ERR), S.red("error: " + msg)), file=sys.stderr)
    sys.exit(2)


def mode_name(v):
    return {ENABLED: "enabled", DISABLED: "DISABLED", ENABLED_PW: "enabled with password"}.get(
        v, "0x%04X (unknown)" % v)


def mode_badge(v):
    text = "%s %s" % (S.DOT, mode_name(v))
    if v == ENABLED:
        return S.green(text)
    if v == ENABLED_PW:
        return S.yellow(text)
    return S.red(text)


# ---------------------------------------------------------------------------
# human readable meaning of the fields (TRM SLAU962, 1.4.2)
# ---------------------------------------------------------------------------

EN_DIS = {ENABLED: "enabled", DISABLED: "disabled"}
EN_DIS_PW = {ENABLED: "enabled", DISABLED: "disabled", ENABLED_PW: "enabled with password"}
# the TRM doesn't give the encoding of these fields: assumed as the others
EN_DIS_ASSUMED = {ENABLED: "enabled (?)", DISABLED: "disabled (?)"}

BAUD = {1: "4800", 2: "9600", 3: "19200", 4: "38400", 5: "57600", 6: "115200",
        7: "1000000", 8: "2000000", 9: "3000000"}


def enum(v, names, width=4):
    if v in names:
        return names[v]
    return ("0x%0*X" % (width, v)) + " (not documented)"


def halves(v, hi_label, hi_names, lo_label, lo_names):
    return [(hi_label, enum(v >> 16, hi_names)), (lo_label, enum(v & 0xFFFF, lo_names))]


def bits_text(v, default):
    n = bin(v).count("1")
    text = "%d of 32 bits set" % n
    if v == default:
        text += " (factory default)"
    return text


def decode(ofs, v):
    """Meaning of a field value: list of (label, text)."""
    if ofs == 0x004:
        return halves(v, "SWD", EN_DIS, "debug access", EN_DIS)
    if ofs == 0x008:
        return halves(v, "debug hold until INITDONE", EN_DIS_ASSUMED, "BSL invoke pin", EN_DIS)
    if ofs == 0x00C:
        return halves(v, "flash bank swap policy", EN_DIS_ASSUMED,
                      "CSC (customer secure code)", EN_DIS)
    if ofs == 0x010:
        return halves(v, "bootloader (BSL)", EN_DIS_ASSUMED, "fast boot", EN_DIS_ASSUMED)
    if ofs == 0x014:
        return halves(v, "factory reset", EN_DIS_PW, "mass erase", EN_DIS_PW)
    if 0x018 <= ofs < 0x0B8 or 0x0C4 <= ofs < 0x0E4 or 0x414 <= ofs < 0x434:
        return [("hash word", "erased (0xFFFFFFFF)" if v == 0xFFFFFFFF else "set")]
    if ofs == 0x0B8:
        return [("secure boot", enum(v & 0xFFFF, {ENABLED: "CRC check of the application",
                                                  ENABLED_PW: "hash check of the application",
                                                  0xFFFF: "disabled"}))]
    if ofs in (0x0BC, 0x0C0):
        return [("value", "0x%08X" % v)]
    if ofs == 0x0E4:
        return [("NONMAIN write protection",
                 "disabled" if (v & 0xFFFF) == ENABLED else
                 "ENABLED (0x%04X): NONMAIN can only be changed by a factory reset" % (v & 0xFFFF))]
    if ofs in (0x0E8, 0x0EC, 0x104, 0x108, 0x120):
        return [("write/erase protection", bits_text(v, 0xFFFFFFFF))]
    if ofs in (0x0F0, 0x0F4, 0x10C, 0x110, 0x124):
        return [("security protection", bits_text(v, 0))]
    if ofs in (0x0F8, 0x0FC, 0x114, 0x118, 0x128):
        return [("privilege protection", bits_text(v, 0))]
    if ofs == 0x130:
        return [("PLL source", enum(v >> 24, {0xAA: "HFXT 20 MHz", 0xBB: "HFXT 40 MHz",
                                              0xFF: "default"}, 2)),
                ("PLL RDIV", "%d" % ((v >> 16) & 0xFF)),
                ("PLL QDIV", "%d" % ((v >> 8) & 0xFF)),
                ("clock", enum(v & 0xFF, {0xAA: "PLL 80 MHz", 0xBB: "PLL custom",
                                          0xFF: "no PLL"}, 2))]
    if ofs == 0x134:
        return [("HFXT monitoring delay", "%d cycles" % ((v >> 8) & 0xFF)),
                ("PLL settling delay", "%d cycles" % (v & 0xFF))]
    if ofs in (0x404, 0x408, 0x40C):
        tx, rx = {0x404: ("UART TXD", "UART RXD"), 0x408: ("I2C SCL", "I2C SDA"),
                  0x40C: ("MCAN TX", "MCAN RX")}[ofs]
        return [(tx, "pad %d, mux %d" % ((v >> 16) & 0xFF, v >> 24)),
                (rx, "pad %d, mux %d" % (v & 0xFF, (v >> 8) & 0xFF))]
    if ofs == 0x410:
        return [("memory readout", enum(v >> 16, EN_DIS_ASSUMED)),
                ("invoke pin data", "0x%02X 0x%02X" % ((v >> 8) & 0xFF, v & 0xFF))]
    if ofs == 0x434:
        return [("application version",
                 "none (0xFFFFFFFF)" if v == 0xFFFFFFFF else "at 0x%08X" % v)]
    if ofs == 0x438:
        return [("UART baud rate", enum(v >> 16, BAUD)),
                ("security alert response", enum(v & 0xFFFF, {ENABLED: "factory reset",
                                                              ENABLED_PW: "disable BSL",
                                                              0xFFFF: "do nothing"}))]
    if ofs == 0x43C:
        return [("I2C slave address", "0x%02X" % (v & 0xFFFF))]
    return []


def print_meaning(ofs, old, new):
    """The parts of a field which change, old and new meaning."""
    dold, dnew = dict(decode(ofs, old)), decode(ofs, new)
    for label, text in dnew:
        before = dold.get(label)
        if before == text:
            continue
        # the old meaning in the column of the values (column 34)
        print("    %-28s  %s %s %s" % (label, S.dim(before), S.yellow(S.ARROW),
                                       S.bold(state_color(text))))


def state_color(text):
    t = text.lower()
    if t.startswith("disabled"):
        return S.red(text)
    if "password" in t or "not documented" in t or t.startswith("enabled (0x"):
        return S.yellow(text)
    return text


def check(img):
    """The same checks as PEEDI before programming (except the config IDs of
    the device, which PEEDI reads from the device).
    Returns (errors, warnings), lists of messages."""
    errors, warnings = [], []

    for name, start, ofs in (("BCR", BCR_START, BCR_CRC), ("BSL", BSL_START, BSL_CRC)):
        crc = crc32_nonmain(img[start:ofs])
        if crc != get32(img, ofs):
            errors.append("%s CRC is 0x%08X, must be 0x%08X" % (name, get32(img, ofs), crc))

    if get32(img, 0x000) in (0, 0xFFFFFFFF) or get32(img, 0x400) in (0, 0xFFFFFFFF):
        errors.append("BCR_CONFIG_ID / BSL_CONFIG_ID is erased (0x%08X / 0x%08X)"
                      % (get32(img, 0x000), get32(img, 0x400)))

    cfg0, cfg4 = get32(img, 0x004), get32(img, 0x014)
    if (cfg0 >> 16) != ENABLED:
        errors.append("BOOTCFG0 = 0x%08X disables the SWD: the device could not be "
                      "debugged or recovered any more (PEEDI refuses it)" % cfg0)
    if (cfg0 & 0xFFFF) == DISABLED and (cfg4 >> 16) == DISABLED:
        errors.append("BOOTCFG0 = 0x%08X and BOOTCFG4 = 0x%08X disable the debug access "
                      "and the factory reset: the device could not be recovered any more "
                      "(PEEDI refuses it)" % (cfg0, cfg4))
    if (get32(img, 0x0E4) & 0xFFFF) != ENABLED:
        warnings.append("BANK0_NM_USER_CONFIG = 0x%08X enables the static write protection of "
                        "NONMAIN: afterwards only a factory reset can change it"
                        % get32(img, 0x0E4))
    if (cfg0 & 0xFFFF) != ENABLED:
        warnings.append("debug access is %s (BOOTCFG0 = 0x%08X)"
                        % (mode_name(cfg0 & 0xFFFF), cfg0))
    if (cfg4 >> 16) != ENABLED:
        warnings.append("factory reset is %s (BOOTCFG4 = 0x%08X)"
                        % (mode_name(cfg4 >> 16), cfg4))
    if (cfg4 & 0xFFFF) != ENABLED:
        warnings.append("mass erase is %s (BOOTCFG4 = 0x%08X)"
                        % (mode_name(cfg4 & 0xFFFF), cfg4))
    return errors, warnings


def print_crcs(img):
    for name, start, ofs in (("BCR", BCR_START, BCR_CRC), ("BSL", BSL_START, BSL_CRC)):
        crc = crc32_nonmain(img[start:ofs])
        if crc == get32(img, ofs):
            ok("%s CRC   %s" % (name, S.bold("0x%08X" % crc)))
        else:
            error("%s CRC   0x%08X, must be 0x%08X" % (name, get32(img, ofs), crc))


def print_security(img):
    cfg0, cfg4 = get32(img, 0x004), get32(img, 0x014)
    for label, v in (("SWD", cfg0 >> 16), ("debug access", cfg0 & 0xFFFF),
                     ("factory reset", cfg4 >> 16), ("mass erase", cfg4 & 0xFFFF)):
        print("  %-15s %s" % (label, mode_badge(v)))


GROUPS = [
    ("BCR  boot configuration", 0x000, 0x018),
    ("BCR  password hashes", 0x018, 0x0B8),
    ("BCR  secure boot", 0x0B8, 0x0E4),
    ("BCR  flash protection", 0x0E4, 0x130),
    ("BCR  boot clock", 0x130, 0x14C),
    ("BCR  CRC", 0x14C, 0x150),
    ("BSL  bootloader configuration", 0x400, 0x44C),
    ("BSL  CRC", 0x44C, 0x450),
]


def print_fields(img, changed=(), values=True):
    for gname, gstart, gend in GROUPS:
        print("  %s" % S.cyan(gname))
        for name, ofs, desc in FIELDS:
            if not gstart <= ofs < gend:
                continue
            addr = S.dim("0x%08X" % (NONMAIN_BASE + ofs))
            if not values:
                print("    %s  %s  %-31s %s" % (S.dim("0x%03X" % ofs), addr, name, S.dim(desc)))
                continue
            val = get32(img, ofs)
            vtxt = "0x%08X" % val
            if ofs in changed:
                vtxt, mark = S.bold(S.yellow(vtxt)), S.yellow(S.STAR)
            elif val == 0xFFFFFFFF:
                vtxt, mark = S.dim(vtxt), " "
            else:
                vtxt, mark = S.bold(vtxt), " "
            print("    %s %s  %-31s %s  %s" % (mark, addr, name, vtxt, S.dim(desc)))
        print()
    if changed:
        note("%s = changed" % S.STAR)


def parse_assign(text, by_name):
    if "=" not in text:
        fatal("'%s': expected NAME=VALUE" % text)
    key, val = text.split("=", 1)
    try:
        val = int(val, 0)
    except ValueError:
        fatal("'%s': the value is not a number" % text)
    if by_name:
        key = key.strip().upper()
        if key not in FIELD_BY_NAME:
            fatal("unknown field '%s' (--list shows the fields)" % key)
        if key in ("BCR_CRC", "BSL_CRC"):
            fatal("%s is computed by the script" % key)
        ofs = FIELD_BY_NAME[key][1]
    else:
        try:
            ofs = int(key, 0)
        except ValueError:
            fatal("'%s': the offset is not a number" % text)
        if ofs >= NONMAIN_BASE:
            ofs -= NONMAIN_BASE
        if ofs % 4 or not 0 <= ofs < NONMAIN_SIZE:
            fatal("offset 0x%X: must be word aligned and < 0x%X" % (ofs, NONMAIN_SIZE))
        if ofs in (BCR_CRC, BSL_CRC):
            fatal("offset 0x%X is a CRC, it is computed by the script" % ofs)
    if not 0 <= val <= 0xFFFFFFFF:
        fatal("'%s': the value is not 32-bit" % text)
    return ofs, val


def main():
    global S

    ap = argparse.ArgumentParser(
        description="Create, change and check NONMAIN images (BCR + BSL boot configuration) "
                    "of the TI MSPM33. See README.md.")
    ap.add_argument("input", nargs="?",
                    help="NONMAIN image: binary (2048 bytes) or text of "
                         "\"memory read32 0x80101800 512\"")
    ap.add_argument("--default", action="store_true",
                    help="start from the built-in factory default (MSPM33C321A) "
                         "instead of an input image")
    ap.add_argument("-o", "--output", help="write the new binary image (CRCs recomputed)")
    ap.add_argument("--set", action="append", default=[], metavar="NAME=VALUE",
                    help="set a field by name, e.g. BOOTCFG1=0xAABB5522 (more than once)")
    ap.add_argument("--set-ofs", action="append", default=[], metavar="OFS=VALUE",
                    help="set a 32-bit word by offset in the sector (or by address 0x801018xx)")
    ap.add_argument("--info", action="store_true", help="print all fields of the (new) image")
    ap.add_argument("--list", action="store_true", help="list the field names and offsets")
    ap.add_argument("--no-color", action="store_true", help="no colors (also: NO_COLOR=1)")
    args = ap.parse_args()

    S = Style(sys.stdout.isatty() and not args.no_color and not os.environ.get("NO_COLOR"))

    if args.list:
        section("NONMAIN fields")
        print_fields(None, values=False)
        return 0

    if args.default and args.input:
        ap.error("either an input image or --default")
    if not args.input and not args.default:
        ap.error("no input image and no --default (--list works without)")

    # check the options before any output
    changes = [parse_assign(t, True) for t in args.set] + \
              [parse_assign(t, False) for t in args.set_ofs]

    if args.default:
        img = default_image()
        source = "built-in factory default (MSPM33C321A)"
    else:
        img = read_image(args.input)
        source = args.input

    box(["%s  %s" % (S.dim("input "), S.bold(source)),
         "%s  %s" % (S.dim("output"), S.bold(args.output) if args.output else S.dim("-"))],
        "MSPM33 NONMAIN")

    section("Input")
    if args.default:
        warn("another device revision may have other defaults: "
             "reading the device's NONMAIN is safer")
    print_crcs(img)

    if changes:
        section("Changes")
        for ofs, val in changes:
            name = next((f[0] for f in FIELDS if f[1] == ofs), "offset 0x%03X" % ofs)
            old = get32(img, ofs)
            print("  %s %s %s %s" % (S.bold("%-31s" % name), S.dim("0x%08X" % old),
                                      S.yellow(S.ARROW), S.bold(S.yellow("0x%08X" % val))))
            if old == val:
                print("    %-28s  %s" % ("", S.dim("(the same value)")))
            else:
                print_meaning(ofs, old, val)
            put32(img, ofs, val)

        # without changes the CRCs are kept: a damaged image stays refused
        update_crc(img)
        print("  %-31s %s" % ("CRCs", S.dim("recomputed")))

    if args.info:
        section("Fields")
        print_fields(img, changed={o for o, _ in changes})

    section("Security")
    print_security(img)

    errors, warnings = check(img)
    section("Check")
    if not errors and not warnings:
        ok("the image is a valid configuration")
    for w in warnings:
        warn(w)
    for e in errors:
        error(e)

    print()
    if args.output:
        if errors:
            box([S.red("%s the image is NOT written" % S.ERR)])
            return 1
        try:
            with open(args.output, "wb") as f:
                f.write(img)
        except OSError as e:
            fatal("%s: %s" % (args.output, e.strerror))
        box(["%s %s" % (S.green(S.OK), S.bold("written: %s" % args.output)),
             "",
             S.dim("program it with (\"NONMAIN = YES\" in the flash section):"),
             S.cyan("flash program %s bin 0x%08X" % (os.path.basename(args.output),
                                                     NONMAIN_BASE))])
    else:
        note("no --output: nothing written")

    return 1 if errors else 0


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