425 lines
16 KiB
Python
425 lines
16 KiB
Python
#!/usr/bin/env python3
|
|
"""Build and package Assembler Casino into the modern CASINO-PACK-V2 installer."""
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import re
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import zipfile
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
FOOTER_MAGIC = b"CASINO-PACK-V2!\n"
|
|
STUDIO_MEDIA = (
|
|
"assets/animations/intro/eblan-studio-v8.hfm",
|
|
"assets/animations/intro/eblan-studio-v8.json",
|
|
"assets/audio/startup/studio-workshop-v8.wav",
|
|
)
|
|
|
|
|
|
def sha256_stream(file_obj, length=None):
|
|
h = hashlib.sha256()
|
|
remaining = length if length is not None else float("inf")
|
|
while remaining > 0:
|
|
chunk_size = min(65536, remaining if length is not None else 65536)
|
|
chunk = file_obj.read(chunk_size)
|
|
if not chunk:
|
|
break
|
|
h.update(chunk)
|
|
if length is not None:
|
|
remaining -= len(chunk)
|
|
return h.hexdigest().lower()
|
|
|
|
|
|
def sha256_file(path):
|
|
with open(path, "rb") as f:
|
|
return sha256_stream(f)
|
|
|
|
|
|
def collect_payload_files():
|
|
entries = []
|
|
for relative in STUDIO_MEDIA:
|
|
if not (ROOT / relative).is_file():
|
|
raise FileNotFoundError(f"Missing studio intro asset: {relative}")
|
|
|
|
# Executables
|
|
for src, dst in [
|
|
(ROOT / "dist/Assembler Casino.exe", "Assembler Casino.exe"),
|
|
(ROOT / "dist/Uninstall Assembler Casino.exe", "Uninstall Assembler Casino.exe"),
|
|
(ROOT / "bin/poker.exe", "bin/poker.exe"),
|
|
(ROOT / "poker.exe", "poker.exe"),
|
|
]:
|
|
if not src.exists():
|
|
raise FileNotFoundError(f"Required binary not found: {src}")
|
|
entries.append((src, dst))
|
|
|
|
# Assets (excluding raw sprites used only for asset generation)
|
|
assets_dir = ROOT / "assets"
|
|
for r, dirs, files in os.walk(assets_dir):
|
|
if Path(r) == assets_dir:
|
|
# Editable Blender/AE projects, scans and source image sequences are
|
|
# offline authoring material. Ship their compiled media, not the set.
|
|
dirs[:] = [d for d in dirs if d not in {"cinematics", "sprites"}]
|
|
if "sprites" in Path(r).parts:
|
|
continue
|
|
for f in sorted(files):
|
|
fp = Path(r) / f
|
|
rel = fp.relative_to(ROOT).as_posix()
|
|
if (
|
|
rel.startswith(("assets/animations/intro/eblan-studio-v", "assets/audio/startup/studio-workshop-v"))
|
|
and rel not in STUDIO_MEDIA
|
|
):
|
|
continue
|
|
entries.append((fp, rel))
|
|
|
|
# Docs
|
|
docs_dir = ROOT / "docs"
|
|
for r, dirs, files in os.walk(docs_dir):
|
|
for f in sorted(files):
|
|
if f.endswith((".txt", ".md")):
|
|
fp = Path(r) / f
|
|
rel = fp.relative_to(ROOT).as_posix()
|
|
entries.append((fp, rel))
|
|
|
|
# Tools
|
|
tool_files = [
|
|
"tools/previews/preview_dbd_hook.bat",
|
|
"tools/previews/preview_hakari.bat",
|
|
"tools/previews/preview_intro.bat",
|
|
"tools/previews/preview_casino3d.bat",
|
|
"tools/tests/achievement_popup.bat",
|
|
"tools/tests/release_smoke_check.ps1",
|
|
]
|
|
for rel in tool_files:
|
|
fp = ROOT / rel
|
|
if fp.exists():
|
|
entries.append((fp, rel))
|
|
|
|
# Backwards compatibility paths for tests / older scripts
|
|
if (ROOT / "tools/previews/preview_dbd_hook.bat").exists():
|
|
entries.append((ROOT / "tools/previews/preview_dbd_hook.bat", "tools/preview_dbd_hook.bat"))
|
|
if (ROOT / "tools/tests/release_smoke_check.ps1").exists():
|
|
entries.append((ROOT / "tools/tests/release_smoke_check.ps1", "tools/release_smoke_check.ps1"))
|
|
|
|
# AI worker & metadata (without models/ directory)
|
|
ai_dir = ROOT / "ai"
|
|
if ai_dir.exists():
|
|
for r, dirs, files in os.walk(ai_dir):
|
|
if "models" in Path(r).parts:
|
|
continue
|
|
for f in sorted(files):
|
|
fp = Path(r) / f
|
|
rel = fp.relative_to(ROOT).as_posix()
|
|
entries.append((fp, rel))
|
|
|
|
# Root documentation & legal
|
|
for rel in ["AGENTS.md", "README.md", "LICENSE"]:
|
|
fp = ROOT / rel
|
|
if fp.exists():
|
|
entries.append((fp, rel))
|
|
|
|
# Clean and deduplicate entries
|
|
unique_entries = []
|
|
seen_dest = set()
|
|
for src, dst in entries:
|
|
clean_dst = dst.replace("\\", "/").lstrip("/")
|
|
if clean_dst not in seen_dest:
|
|
seen_dest.add(clean_dst)
|
|
unique_entries.append((src, clean_dst))
|
|
|
|
return unique_entries
|
|
|
|
|
|
def build_payload_zip(zip_path, entries):
|
|
print(f"Creating game archive: {zip_path} ({len(entries)} files)...")
|
|
zip_path.parent.mkdir(parents=True, exist_ok=True)
|
|
uncompressed_bytes = 0
|
|
with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=4) as zf:
|
|
for src, dst in entries:
|
|
zf.write(src, dst)
|
|
uncompressed_bytes += src.stat().st_size
|
|
size_mb = zip_path.stat().st_size / (1024 * 1024)
|
|
print(f"Game archive created: {size_mb:.2f} MB (uncompressed: {uncompressed_bytes / (1024*1024):.2f} MB)")
|
|
return uncompressed_bytes
|
|
|
|
|
|
def compile_installer_base(index_sha256):
|
|
installer_dir = ROOT / "build/installer"
|
|
stamp_path = installer_dir / "PokerGameSetup/PackageStamp.cs"
|
|
|
|
stamp_content = f"""namespace PokerGameSetup;
|
|
|
|
internal static class PackageStamp
|
|
{{
|
|
\tpublic const string IndexSha256 = "{index_sha256}";
|
|
}}
|
|
"""
|
|
stamp_path.write_text(stamp_content, encoding="utf-8")
|
|
print(f"Updated PackageStamp.cs with IndexSha256: {index_sha256}")
|
|
|
|
out_dir = installer_dir / "bin"
|
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
cmd = [
|
|
"dotnet",
|
|
"build",
|
|
str(installer_dir / "PokerGameSetup.csproj"),
|
|
"-c",
|
|
"Release",
|
|
"-o",
|
|
str(out_dir),
|
|
]
|
|
print(f"Compiling installer base: {' '.join(cmd)}")
|
|
res = subprocess.run(cmd, capture_output=True, text=True)
|
|
if res.returncode != 0:
|
|
raise RuntimeError(f"dotnet build failed:\n{res.stdout}\n{res.stderr}")
|
|
|
|
base_exe = out_dir / "Setup-base.exe"
|
|
if not base_exe.exists():
|
|
base_exe = out_dir / "PokerGameSetup.exe"
|
|
if not base_exe.exists():
|
|
raise FileNotFoundError(f"Compiled setup base executable not found in {out_dir}")
|
|
|
|
print(f"Compiled base executable: {base_exe} ({base_exe.stat().st_size} bytes)")
|
|
return base_exe
|
|
|
|
|
|
def verify_package(setup_path, expected_index_sha256, has_model, expected_model_sha256=None):
|
|
print(f"Verifying package {setup_path}...")
|
|
size = setup_path.stat().st_size
|
|
if size < 32:
|
|
raise ValueError("Package too small to contain footer")
|
|
|
|
with open(setup_path, "rb") as f:
|
|
f.seek(-32, os.SEEK_END)
|
|
footer = f.read(32)
|
|
payload_offset, index_len, magic = struct.unpack("<qq16s", footer)
|
|
|
|
if magic != FOOTER_MAGIC:
|
|
raise ValueError(f"Invalid footer magic: {magic}")
|
|
if index_len < 1 or index_len > 16777216:
|
|
raise ValueError(f"Invalid index length: {index_len}")
|
|
if payload_offset < 0 or payload_offset > size - 32 - index_len:
|
|
raise ValueError(f"Invalid payload offset: {payload_offset}")
|
|
|
|
index_offset = size - 32 - index_len
|
|
f.seek(index_offset)
|
|
index_bytes = f.read(index_len)
|
|
actual_index_hash = hashlib.sha256(index_bytes).hexdigest().lower()
|
|
if actual_index_hash != expected_index_sha256.lower():
|
|
raise ValueError(f"Index hash mismatch: {actual_index_hash} != {expected_index_sha256}")
|
|
|
|
# Test reading game zip slice
|
|
f.seek(payload_offset)
|
|
# Parse XML index
|
|
import xml.etree.ElementTree as ET
|
|
root = ET.fromstring(index_bytes.decode("utf-8"))
|
|
if root.tag != "casino-package":
|
|
raise ValueError(f"Invalid root tag: {root.tag}")
|
|
|
|
game_elem = root.find("game")
|
|
if game_elem is None:
|
|
raise ValueError("Missing <game> element")
|
|
|
|
game_offset = int(game_elem.attrib["offset"])
|
|
game_len = int(game_elem.attrib["length"])
|
|
game_bytes = int(game_elem.attrib["bytes"])
|
|
game_sha256 = game_elem.attrib["sha256"]
|
|
|
|
if game_offset != 0:
|
|
raise ValueError("Game offset must be 0")
|
|
|
|
f.seek(payload_offset + game_offset)
|
|
actual_game_hash = sha256_stream(f, game_len)
|
|
if actual_game_hash != game_sha256.lower():
|
|
raise ValueError(f"Game hash mismatch: {actual_game_hash} != {game_sha256}")
|
|
|
|
# Check zip archive validity
|
|
class SliceIO:
|
|
def __init__(self, f_obj, start, length):
|
|
self._f = f_obj
|
|
self._start = start
|
|
self._length = length
|
|
self._pos = 0
|
|
|
|
def read(self, n=-1):
|
|
if n < 0 or self._pos + n > self._length:
|
|
n = self._length - self._pos
|
|
if n <= 0:
|
|
return b""
|
|
self._f.seek(self._start + self._pos)
|
|
data = self._f.read(n)
|
|
self._pos += len(data)
|
|
return data
|
|
|
|
def seek(self, offset, whence=0):
|
|
if whence == 0:
|
|
self._pos = offset
|
|
elif whence == 1:
|
|
self._pos += offset
|
|
elif whence == 2:
|
|
self._pos = self._length + offset
|
|
self._pos = max(0, min(self._pos, self._length))
|
|
return self._pos
|
|
|
|
def tell(self):
|
|
return self._pos
|
|
|
|
sio = SliceIO(f, payload_offset + game_offset, game_len)
|
|
with zipfile.ZipFile(sio, "r") as zf:
|
|
uncompressed = sum(info.file_size for info in zf.infolist())
|
|
if uncompressed != game_bytes:
|
|
raise ValueError(f"Uncompressed bytes mismatch: {uncompressed} != {game_bytes}")
|
|
for info in zf.infolist():
|
|
if info.filename.endswith("/") or info.is_dir() or not info.filename.split("/")[-1]:
|
|
raise ValueError(f"Forbidden directory entry in zip: {info.filename}")
|
|
if "\\" in info.filename:
|
|
raise ValueError(f"Forbidden backslash in entry: {info.filename}")
|
|
|
|
# Check model if present
|
|
model_elem = root.find("model")
|
|
if has_model:
|
|
if model_elem is None:
|
|
raise ValueError("Expected <model> element not found in index")
|
|
model_offset = int(model_elem.attrib["offset"])
|
|
model_len = int(model_elem.attrib["length"])
|
|
model_bytes = int(model_elem.attrib["bytes"])
|
|
model_sha256 = model_elem.attrib["sha256"]
|
|
|
|
if model_offset != game_len:
|
|
raise ValueError(f"Model offset {model_offset} != game length {game_len}")
|
|
if model_bytes != model_len:
|
|
raise ValueError(f"Model bytes {model_bytes} != model length {model_len}")
|
|
|
|
f.seek(payload_offset + model_offset)
|
|
actual_model_hash = sha256_stream(f, model_len)
|
|
if actual_model_hash != model_sha256.lower():
|
|
raise ValueError(f"Model hash mismatch: {actual_model_hash} != {model_sha256}")
|
|
if expected_model_sha256 and actual_model_hash != expected_model_sha256.lower():
|
|
raise ValueError(f"Model hash mismatch with expected: {actual_model_hash}")
|
|
else:
|
|
if model_elem is not None:
|
|
raise ValueError("Unexpected <model> element found when has_model is False")
|
|
|
|
print("[VERIFIED] Package passed all structural and cryptographic checks!")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description="Build modern Assembler Casino installer.")
|
|
parser.add_argument("--no-model", action="store_true", help="Build installer without the 2.5 GB offline model")
|
|
parser.add_argument("--output", type=str, default="", help="Custom output installer filename")
|
|
args = parser.parse_args()
|
|
|
|
include_model = not args.no_model
|
|
|
|
if args.output:
|
|
output_name = args.output
|
|
else:
|
|
output_name = "PokerGameSetup.exe" if include_model else "PokerGameSetup_NoModel.exe"
|
|
|
|
output_exe = ROOT / output_name
|
|
print(f"=== Building Assembler Casino Installer: {output_name} ===")
|
|
print(f"Include offline fortune model: {include_model}")
|
|
|
|
# 1. Model verification (if enabled)
|
|
model_path = None
|
|
model_len = 0
|
|
model_sha256 = ""
|
|
model_target_rel = "ai/models/fortune-qwen3-4b-q4_k_m.gguf"
|
|
|
|
if include_model:
|
|
manifest_path = ROOT / "ai/model.json"
|
|
if not manifest_path.exists():
|
|
raise FileNotFoundError(f"Model manifest not found: {manifest_path}")
|
|
manifest = json.loads(manifest_path.read_text("utf-8"))
|
|
model_path = ROOT / "ai" / manifest["file"]
|
|
if not model_path.exists():
|
|
raise FileNotFoundError(
|
|
f"Offline fortune model not found at {model_path}. "
|
|
"Run download_fortune_model.bat to download it, or use --no-model."
|
|
)
|
|
model_len = model_path.stat().st_size
|
|
expected_len = manifest["bytes"]
|
|
if model_len != expected_len:
|
|
raise ValueError(f"Model size mismatch: {model_len} != {expected_len}")
|
|
|
|
print(f"Verifying offline model hash ({model_path.name})...")
|
|
model_sha256 = manifest["sha256"].lower()
|
|
actual_hash = sha256_file(model_path)
|
|
if actual_hash != model_sha256:
|
|
raise ValueError(f"Model SHA-256 mismatch: {actual_hash} != {model_sha256}")
|
|
print(f"Model verified: {model_len / (1024*1024):.2f} MB, SHA-256: {model_sha256}")
|
|
|
|
# 2. Collect and zip game payload
|
|
entries = collect_payload_files()
|
|
payload_zip = ROOT / "build/payload_release_final.zip"
|
|
uncompressed_bytes = build_payload_zip(payload_zip, entries)
|
|
game_zip_len = payload_zip.stat().st_size
|
|
game_zip_sha256 = sha256_file(payload_zip)
|
|
print(f"Game ZIP SHA-256: {game_zip_sha256}")
|
|
|
|
# 3. Construct XML index
|
|
if include_model:
|
|
xml_index = (
|
|
f"<?xml version='1.0' encoding='utf-8'?>\n"
|
|
f'<casino-package version="2">'
|
|
f'<game offset="0" length="{game_zip_len}" bytes="{uncompressed_bytes}" sha256="{game_zip_sha256}" />'
|
|
f'<model offset="{game_zip_len}" length="{model_len}" bytes="{model_len}" sha256="{model_sha256}" path="{model_target_rel}" />'
|
|
f"</casino-package>"
|
|
)
|
|
else:
|
|
xml_index = (
|
|
f"<?xml version='1.0' encoding='utf-8'?>\n"
|
|
f'<casino-package version="2">'
|
|
f'<game offset="0" length="{game_zip_len}" bytes="{uncompressed_bytes}" sha256="{game_zip_sha256}" />'
|
|
f"</casino-package>"
|
|
)
|
|
|
|
xml_bytes = xml_index.encode("utf-8")
|
|
index_sha256 = hashlib.sha256(xml_bytes).hexdigest().lower()
|
|
print(f"XML Index SHA-256: {index_sha256}")
|
|
|
|
# 4. Compile base setup executable with index SHA-256 stamped
|
|
base_exe = compile_installer_base(index_sha256)
|
|
base_len = base_exe.stat().st_size
|
|
|
|
# 5. Assemble final installer executable
|
|
print(f"Assembling {output_exe}...")
|
|
with open(output_exe, "wb") as out_f:
|
|
# Write base executable
|
|
with open(base_exe, "rb") as in_base:
|
|
out_f.write(in_base.read())
|
|
|
|
# Stream game zip
|
|
print("Writing game archive...")
|
|
with open(payload_zip, "rb") as in_zip:
|
|
while chunk := in_zip.read(1048576):
|
|
out_f.write(chunk)
|
|
|
|
# Stream model (if included)
|
|
if include_model:
|
|
print("Writing offline neural model (2.5 GB)...")
|
|
with open(model_path, "rb") as in_model:
|
|
while chunk := in_model.read(1048576):
|
|
out_f.write(chunk)
|
|
|
|
# Write XML index
|
|
print("Writing XML index and footer...")
|
|
out_f.write(xml_bytes)
|
|
|
|
# Write 32-byte footer: <payload_offset: long><index_len: long><magic: 16 bytes>
|
|
footer_bytes = struct.pack("<qq16s", base_len, len(xml_bytes), FOOTER_MAGIC)
|
|
out_f.write(footer_bytes)
|
|
|
|
total_mb = output_exe.stat().st_size / (1024 * 1024)
|
|
print(f"=== Successfully built {output_exe} ({total_mb:.2f} MB / {output_exe.stat().st_size / 1e9:.2f} GB) ===")
|
|
|
|
# 6. Verify built setup
|
|
verify_package(output_exe, index_sha256, include_model, model_sha256 if include_model else None)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|