#!/bin/bash
# mkcd.sh  -- Build DVX and create a CD-ROM ISO image for 86Box
#
# Usage: ./mkcd.sh
#
# Builds the full DVX stack (dvx, tasks, shell, apps), then creates
# an ISO 9660 image from the bin/ directory.  The ISO uses short
# 8.3 filenames (-iso-level 1) for DOS compatibility.
#
# The ISO is placed in 86Box's data directory so it can be mounted
# as a CD-ROM drive.

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ISO_DIR="$HOME/.var/app/net._86box._86Box/data/86Box"
ISO_PATH="$ISO_DIR/dvx.iso"

# Build everything
echo "Building DVX..."
make -C "$SCRIPT_DIR" all

# Verify core build output exists
for f in dvx.exe libs/kpunch/libtasks/libtasks.lib libs/kpunch/libdvx/libdvx.lib libs/kpunch/dvxshell/dvxshell.lib; do
    if [ ! -f "$SCRIPT_DIR/bin/$f" ]; then
        echo "ERROR: bin/$f not found  -- build failed?"
        exit 1
    fi
done

# Verify widget DXEs exist
WGT_COUNT=0
while IFS= read -r f; do
    WGT_COUNT=$((WGT_COUNT + 1))
done < <(find "$SCRIPT_DIR/bin/widgets/" -name "*.wgt" -type f 2>/dev/null)
echo "$WGT_COUNT widget modules found in bin/widgets/."

# Clean DOSBox-X local filesystem artifacts
find "$SCRIPT_DIR/bin/" -name ".DBLOCALFILE*" -delete 2>/dev/null

# Create the ISO image
# -iso-level 1: strict 8.3 filenames (DOS compatibility)
# -J: Joliet extensions (long names for Windows/Linux)
# -V: volume label
# Note: -R (Rock Ridge) is omitted because DOS surfaces its
#       attribute sidecar files (._ATR_) as visible junk files.
echo "Creating ISO image..."
mkisofs \
    -iso-level 1 \
    -J \
    -V "DVX" \
    -o "$ISO_PATH" \
    "$SCRIPT_DIR/bin/"

echo "ISO created: $ISO_PATH"
echo "Size: $(du -h "$ISO_PATH" | cut -f1)"
echo ""
echo "In 86Box, mount $ISO_PATH as a CD-ROM drive."
echo "Then from DOS:  D:\\DVX.EXE  (or whatever drive letter)"
