#!/usr/bin/env bash
# Render the frames and pack bootanimation.zip.
#
# The zip MUST be stored, not deflated: bootanimation mmaps entries straight
# out of the archive and a compressed member is simply not played. `zip -0`
# is the whole reason this is a script rather than one python call.
set -euo pipefail
cd "$(dirname "$0")"

FRAMES="${FRAMES_DIR:-../../out/bootanim/frames}"
OUT="${OUT_DIR:-../../out/bootanim}"
ZIP="$OUT/bootanimation.zip"

mkdir -p "$OUT"
rm -f "$ZIP"

echo "== frames"
python3 make.py "$FRAMES"

echo "== desc.txt"
cat "$FRAMES/desc.txt"

echo "== pack (stored)"
# desc.txt first: the player reads it before scanning members, and putting it
# at the head costs nothing.
( cd "$FRAMES" && zip -0 -q -X "$OLDPWD/$ZIP" desc.txt && zip -0 -q -rX "$OLDPWD/$ZIP" part0 part1 part2 )

echo "== verify"
python3 - "$ZIP" <<'PY'
import sys, zipfile
z = zipfile.ZipFile(sys.argv[1])
names = z.namelist()
bad = [i.filename for i in z.infolist() if i.compress_type != zipfile.ZIP_STORED]
assert not bad, f"compressed members would not play: {bad[:5]}"
assert "desc.txt" in names, "no desc.txt"
desc = z.read("desc.txt").decode().splitlines()
w, h, fps = desc[0].split()
parts = [l.split() for l in desc[1:] if l.strip()]
counts = {}
for p in parts:
    folder = p[3]
    counts[folder] = sum(1 for n in names if n.startswith(folder + "/") and n.endswith(".png"))
    assert counts[folder] > 0, f"{folder} has no frames"
    # Lexicographic order is play order, so zero padding has to be uniform.
    fs = sorted(n for n in names if n.startswith(folder + "/") and n.endswith(".png"))
    lens = {len(n.rsplit("/", 1)[1]) for n in fs}
    assert len(lens) == 1, f"{folder} frame names are not uniformly padded: {lens}"
from PIL import Image
import io
for folder in counts:
    one = next(n for n in names if n.startswith(folder + "/") and n.endswith(".png"))
    im = Image.open(io.BytesIO(z.read(one)))
    assert im.size == (int(w), int(h)), f"{one} is {im.size}, desc says {w}x{h}"
total = sum(counts.values())
print(f"   {w}x{h} @ {fps}fps, {len(parts)} parts, {total} frames, all STORED")
for p in parts:
    print(f"   {p[3]}: type={p[0]} loop={p[1]} pause={p[2]} frames={counts[p[3]]}")
PY

ls -l "$ZIP"
sha256sum "$ZIP"
