#!/bin/bash

# The MIT License (MIT)
#
# Copyright (C) 2026 Scott Duensing
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

# mkcd.sh  -- Build DVX and create a CD-ROM ISO image for the target emulator
#
# 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 the emulator'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 emulator 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 "Mount $ISO_PATH as a CD-ROM drive in the target emulator."
echo "Then from DOS:  D:\\DVX.EXE  (or whatever drive letter)"
