#!/bin/sh
# Regenerate the things that are derived from something else, so they cannot
# drift: the key table in USAGE.md (from the binary) and the font atlas (from
# the TTF).
set -e
cd "$(dirname "$0")/.."

if [ "$1" = "--font" ]; then
  # Bakes every size in SIZES into one flat coverage blob, and rewrites the
  # FONTS table that indexes into it.  The offsets are the only thing tying
  # the blob and the table together, so they are generated in one place.
  python3 - <<'FONTPY'
from PIL import Image, ImageDraw, ImageFont
import re

FONT = "/usr/share/fonts/TTF/DejaVuSansMono.ttf"
SIZES = [13, 16, 20, 26]
lo, hi = 32, 127

blob = bytearray()
rows = []
for size in SIZES:
    f = ImageFont.truetype(FONT, size)
    asc, desc = f.getmetrics()
    ch = asc + desc
    cw = int(round(f.getlength("M")))
    rows.append((size, cw, ch, len(blob)))
    for c in range(lo, hi):
        img = Image.new("L", (cw, ch), 0)
        ImageDraw.Draw(img).text((0, 0), chr(c), font=f, fill=255)
        px = img.load()
        blob += bytes(px[x, y] for y in range(ch) for x in range(cw))

open("crates/wave-render/src/font_atlas.bin", "wb").write(blob)

table = "pub static FONTS: [Font; %d] = [\n" % len(rows)
for size, cw, ch, off in rows:
    table += "    Font { px: %d, cw: %d, ch: %d, off: %d },\n" % (size, cw, ch, off)
table += "];\n"

src = open("crates/wave-render/src/font.rs").read()
src = re.sub(r"pub static FONTS: \[Font; \d+\] = \[.*?\];\n", table, src, flags=re.S)
open("crates/wave-render/src/font.rs", "w").write(src)
print("font atlas regenerated: %d bytes, sizes %s" % (len(blob), [r[0] for r in rows]))
FONTPY
fi

cargo build --release >/dev/null
python3 - <<'KEYPY'
import subprocess, re
keys = subprocess.run(["target/release/waveview","--keys-md"],capture_output=True,text=True).stdout
s = open("docs/USAGE.md").read()
s = re.sub(r"(## Keys and mouse\n\nAlso available.*?\n\n)(\|.*?\n)+",
           lambda m: m.group(1) + keys, s, flags=re.S)
open("docs/USAGE.md","w").write(s)
print("USAGE.md key table refreshed")
KEYPY
