#!/usr/bin/env python3 """Prepare a clean, validated mod-ui pedalboard once per system boot.""" import argparse import hashlib import os import shutil import sys import tempfile from pathlib import Path, PurePosixPath import yaml ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts")) from generate_mod_ui_pedalboard import generate_bundle_files def bundle_digest(files): digest = hashlib.sha256() for name, content in sorted(files.items()): digest.update(name.encode("utf-8") + b"\0" + content + b"\0") return digest.hexdigest() def destination_under_home(home, relative): relative = Path(relative) if relative.is_absolute() or ".." in relative.parts: raise ValueError(f"unsafe mod-ui path: {relative}") destination = home / relative if not destination.resolve().is_relative_to(home.resolve()): raise ValueError(f"mod-ui path escapes the user home directory: {destination}") return destination def validate_generated_bundle(files): required = { "manifest.ttl", "rigforge-guitar.ttl", "addressings.json", "snapshots.json", "effect-0/manifest.ttl", "effect-0/effect.ttl", "effect-1/manifest.ttl", "effect-1/effect.ttl", "screenshot.png", "thumbnail.png", } missing = required - set(files) if missing: raise RuntimeError( "generated pedalboard is missing required files: " + ", ".join(sorted(missing)) ) empty = sorted(name for name, content in files.items() if not content) if empty: raise RuntimeError( "generated pedalboard contains empty files: " + ", ".join(empty) ) graph = files["rigforge-guitar.ttl"].decode("utf-8") if "pedal:Pedalboard" not in graph or "ingen:block , " not in graph: raise RuntimeError("generated pedalboard graph is incomplete") def read_bundle(directory): if directory.is_symlink() or not directory.is_dir(): raise RuntimeError(f"pedalboard bundle is missing or not a directory: {directory}") files = {} for path in directory.rglob("*"): if path.is_symlink(): raise RuntimeError(f"pedalboard bundle contains a symlink: {path}") if path.is_file(): files[path.relative_to(directory).as_posix()] = path.read_bytes() return files def validate_existing_default(directory): if directory.is_symlink() or not directory.is_dir(): raise RuntimeError(f"prepared default pedalboard is unavailable: {directory}") for name in ("manifest.ttl", "rigforge-guitar.ttl"): path = directory / name if path.is_symlink() or not path.is_file() or path.stat().st_size == 0: raise RuntimeError( f"default pedalboard is invalid after boot preparation: {path}" ) graph = (directory / "rigforge-guitar.ttl").read_text(encoding="utf-8") if "pedal:Pedalboard" not in graph: raise RuntimeError(f"default pedalboard graph is invalid: {directory}") def next_backup_path(path, boot_id, backup_directory=None): parent = backup_directory or path.parent parent.mkdir(parents=True, exist_ok=True) base = parent / f"{path.name}.rigforge-boot-backup-{boot_id}" candidate = base suffix = 2 while candidate.exists() or candidate.is_symlink(): candidate = base.with_name(f"{base.name}.{suffix}") suffix += 1 return candidate def is_legacy_pedalboard_backup(path): return ( path.name == "default.pedalboard.rigforge-backup" or path.name.startswith("default.pedalboard.rigforge-reset-backup") or path.name.startswith("default.pedalboard.rigforge-boot-backup-") ) def next_migrated_backup_path(backup_directory, original, boot_id): candidate = backup_directory / original.name if not candidate.exists() and not candidate.is_symlink(): return candidate base = backup_directory / f"{original.name}.migrated-{boot_id}" candidate = base suffix = 2 while candidate.exists() or candidate.is_symlink(): candidate = backup_directory / f"{base.name}.{suffix}" suffix += 1 return candidate def migrate_legacy_pedalboard_backups(pedalboards, backup_directory, boot_id): if not pedalboards.is_dir() or pedalboards.is_symlink(): return legacy = sorted(path for path in pedalboards.iterdir() if is_legacy_pedalboard_backup(path)) if not legacy: return backup_directory.mkdir(parents=True, exist_ok=True) for path in legacy: if path.is_symlink(): raise RuntimeError(f"refusing to migrate a symlinked pedalboard backup: {path}") if not path.is_dir(): raise RuntimeError(f"legacy pedalboard backup is not a directory: {path}") destination = next_migrated_backup_path(backup_directory, path, boot_id) os.replace(path, destination) print(f"Moved legacy mod-ui backup outside pedalboard scan path: {destination}") def write_staged_bundle(files, destination): destination.parent.mkdir(parents=True, exist_ok=True) staged = Path( tempfile.mkdtemp(prefix=f".{destination.name}.rigforge-new-", dir=destination.parent) ) try: for relative, content in files.items(): relative_path = PurePosixPath(relative) if relative_path.is_absolute() or ".." in relative_path.parts: raise RuntimeError(f"unsafe generated pedalboard path: {relative}") path = staged.joinpath(*relative_path.parts) path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(content) if read_bundle(staged) != files: raise RuntimeError(f"staged pedalboard verification failed: {staged}") return staged except BaseException: shutil.rmtree(staged, ignore_errors=True) raise def atomic_write_marker(marker, boot_id): marker.parent.mkdir(parents=True, exist_ok=True) fd, temporary_name = tempfile.mkstemp(prefix=f".{marker.name}.", dir=marker.parent) try: with os.fdopen(fd, "w", encoding="utf-8") as stream: stream.write(boot_id + "\n") os.replace(temporary_name, marker) finally: if os.path.exists(temporary_name): os.unlink(temporary_name) def prepare_pedalboard(state, repo_root, home, runtime_dir, boot_id): config = state["deployment"]["mod_ui"] marker = runtime_dir / "prepared-boot-id" default_board = destination_under_home( home, Path(config["pedalboards_directory"]) / "default.pedalboard" ) last_state = destination_under_home(home, config["last_state_file"]) backup_directory = destination_under_home( home, Path(config["last_state_file"]).parent / "boot-backups" ) migrate_legacy_pedalboard_backups( default_board.parent, backup_directory, boot_id ) if marker.is_file() and marker.read_text(encoding="utf-8").strip() == boot_id: validate_existing_default(default_board) print("mod-ui pedalboard already prepared during this boot; preserving session state") return nam = state["routing"]["mod_host_chains"]["guitar"]["processors"][0] nam_model_path = destination_under_home( home, Path(config["user_files_directory"]) / "NAM Models" / "Rigforge" / Path(nam["asset_path"]).name, ) files = generate_bundle_files( state, repo_root=repo_root, nam_model_path=nam_model_path ) validate_generated_bundle(files) reference = destination_under_home( home, Path(config["reference_directory"]) / f"rigforge-guitar-{bundle_digest(files)[:16]}.pedalboard", ) for path in (reference, default_board): if path.is_symlink(): raise RuntimeError(f"refusing to replace a mod-ui symlink: {path}") if path.exists() and not path.is_dir(): raise RuntimeError(f"mod-ui pedalboard path is not a directory: {path}") if last_state.is_symlink(): raise RuntimeError(f"refusing to move a mod-ui state symlink: {last_state}") if last_state.exists() and not last_state.is_file(): raise RuntimeError(f"mod-ui last-state path is not a file: {last_state}") reference_files = ( read_bundle(reference) if reference.exists() else None ) replace_reference = reference_files != files staged_reference = write_staged_bundle(files, reference) if replace_reference else None staged_default = write_staged_bundle(files, default_board) backups = [] installed = [] try: if replace_reference and reference.exists(): backup = next_backup_path(reference, boot_id) os.replace(reference, backup) backups.append((reference, backup)) if default_board.exists(): backup = next_backup_path(default_board, boot_id, backup_directory) os.replace(default_board, backup) backups.append((default_board, backup)) if last_state.exists(): backup = next_backup_path(last_state, boot_id, backup_directory) os.replace(last_state, backup) backups.append((last_state, backup)) if staged_reference is not None: os.replace(staged_reference, reference) installed.append(reference) os.replace(staged_default, default_board) installed.append(default_board) validate_existing_default(default_board) atomic_write_marker(marker, boot_id) except BaseException: for path in reversed(installed): if path.is_dir() and not path.is_symlink(): shutil.rmtree(path) elif path.exists() or path.is_symlink(): path.unlink() for original, backup in reversed(backups): if backup.exists() or backup.is_symlink(): os.replace(backup, original) raise finally: for staged in (staged_reference, staged_default): if staged is not None and staged.exists(): shutil.rmtree(staged, ignore_errors=True) print(f"Prepared a clean mod-ui pedalboard for boot {boot_id}") def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--state", type=Path, default=ROOT / "config" / "desired-state.yaml") parser.add_argument("--runtime-dir", type=Path, required=True) args = parser.parse_args(argv) try: state = yaml.safe_load(args.state.read_text(encoding="utf-8")) boot_id = Path("/proc/sys/kernel/random/boot_id").read_text(encoding="ascii").strip() if not boot_id: raise RuntimeError("could not determine the current system boot ID") prepare_pedalboard( state, repo_root=ROOT, home=Path.home(), runtime_dir=args.runtime_dir, boot_id=boot_id, ) except (OSError, RuntimeError, ValueError, KeyError) as error: print(f"ERROR: {error}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": raise SystemExit(main())