#!/usr/bin/env bash
# Extracts the C64 and 1541 ROMs needed by vice_jni.c from vice-3.8.tar.gz.
#
# This is a manual/standalone equivalent of the `extractViceRoms` Gradle task
# in app/build.gradle.kts — same source paths, same renaming. Useful for
# inspecting the ROMs outside a full Gradle build (e.g. for the "bring your
# own ROM" flow described in docs/publish.md §0).
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TARBALL="$SCRIPT_DIR/vice-3.8.tar.gz"
DEST="${1:-$SCRIPT_DIR/roms}"

if [[ ! -f "$TARBALL" ]]; then
    echo "error: $TARBALL not found" >&2
    exit 1
fi

mkdir -p "$DEST"
WORK_DIR="$(mktemp -d)"
trap 'rm -rf "$WORK_DIR"' EXIT

tar -xzf "$TARBALL" -C "$WORK_DIR" \
    vice-3.8/data/C64/kernal-901227-03.bin \
    vice-3.8/data/C64/basic-901226-01.bin \
    vice-3.8/data/C64/chargen-901225-01.bin \
    "vice-3.8/data/DRIVES/dos1541-325302-01+901229-05.bin"

cp "$WORK_DIR/vice-3.8/data/C64/kernal-901227-03.bin"            "$DEST/kernal"
cp "$WORK_DIR/vice-3.8/data/C64/basic-901226-01.bin"             "$DEST/basic"
cp "$WORK_DIR/vice-3.8/data/C64/chargen-901225-01.bin"           "$DEST/chargen"
cp "$WORK_DIR/vice-3.8/data/DRIVES/dos1541-325302-01+901229-05.bin" "$DEST/1541"

echo "Extracted kernal, basic, chargen, 1541 to $DEST"
