#!/usr/bin/env python3
import sys

MASK32 = 0xFFFFFFFF
SIGNATURE_SEED = 0x16600122
BITS = (
    0x00000000,
    0x80000000,
    0x00000001,
    0x007FFFFF,
    0x00800000,
    0x3F800000,
    0xC0200000,
    0x7FC12345,
)
INITIAL = (
    (0x1000, 0x3F800000),
    (0x1001, 0xC0200000),
    (0x1002, 0x00000001),
    (0x1003, 0x80000000),
    (0x1004, 0x3F800000),
    (0x1005, 0xC0200000),
)


def step(signature, case_id, actual):
    tag = ((case_id & 0xFFFF) << 16) | (case_id & 0xFFFF)
    return (((signature << 5) | (signature >> 27)) ^ actual ^ tag) & MASK32


def signature():
    value = SIGNATURE_SEED
    for case_id, actual in INITIAL:
        value = step(value, case_id, actual)
    for vector_id, bits in enumerate(BITS, 1):
        for route in range(12):
            value = step(value, 0x2000 + (vector_id - 1) * 12 + route, bits)
    return value


def vectors():
    print("#ifndef FLOAT32_STORAGE_VECTORS_INC")
    print("#define FLOAT32_STORAGE_VECTORS_INC")
    print()
    print("#define ABI_FLOAT32_STORAGE_VECTORS(X) \\")
    for vector_id, bits in enumerate(BITS, 1):
        suffix = " \\" if vector_id != len(BITS) else ""
        print(f"  X({vector_id}, 0x{bits:08x}UL){suffix}")
    print(f"#define ABI_FLOAT32_STORAGE_VECTOR_COUNT {len(BITS)}U")
    print(f"#define ABI_FLOAT32_STORAGE_SIGNATURE 0x{signature():08x}UL")
    print()
    print("#endif")


if len(sys.argv) != 2 or sys.argv[1] not in {"vectors", "signature"}:
    raise SystemExit(
        "usage: gen-float32-storage-vectors vectors|signature"
    )
if sys.argv[1] == "vectors":
    vectors()
else:
    print(signature())
