#!/usr/bin/env bash
# Part of JoeyLib, Copyright (c) 2026 Scott Duensing, under the MIT License.
# See LICENSE.md for license information.
# SPDX-License-Identifier: MIT
#
# joeymod: convert a Protracker .MOD into the runtime form a target
# platform expects.
#
# Usage:
#   joeymod input.mod output.mod     -- passthrough copy + magic validation
#                                       (the module player on DOS, the ST,
#                                       the X68000 and the hosted ports
#                                       finds the song's end itself, so the
#                                       file is used as-is)
#   joeymod input.mod output.amod    -- passthrough + E8F stop-marker
#                                       pattern injected at song end. The
#                                       Amiga audio HAL adds the same
#                                       marker itself to any module played
#                                       with loop false (PTPlayer has no
#                                       native song-end signal), so this is
#                                       only marking ahead of time. Other
#                                       replayers ignore E8, so .amod is
#                                       harmless if fed to the wrong port.
#   joeymod input.mod output.ntp     -- NinjaTrackerPlus' .NTP runtime
#                                       format on the IIgs (modToNtp)
#
# The output extension picks the conversion. Build rules per platform
# call this with whichever pair their HAL needs.

set -euo pipefail

if [[ $# -ne 2 ]]; then
    echo "usage: joeymod input.mod output.{mod,amod,ntp}" >&2
    exit 2
fi

in=$1
out=$2
repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
# shellcheck source=scripts/lib/joeyEnv.sh
source "$repo/scripts/lib/joeyEnv.sh"

if [[ ! -f $in ]]; then
    echo "joeymod: input not found: $in" >&2
    exit 2
fi

# All Protracker-derived .MOD variants store a 4-byte signature at
# offset 1080. Reject anything that does not match a known one --
# better to fail at build time than ship a corrupted audio asset.
magic=$(dd if="$in" bs=1 count=4 skip=1080 status=none)
case "$magic" in
    M.K.|M!K!|FLT4|FLT8|6CHN|8CHN|CD81|OKTA|OCTA) ;;
    *)
        printf 'joeymod: %s does not look like a .MOD (magic %q at offset 1080)\n' "$in" "$magic" >&2
        exit 2
        ;;
esac

ext="${out##*.}"
ext="${ext,,}"

case "$ext" in
    mod)
        cp "$in" "$out"
        ;;
    amod)
        modloopend="$(joeyTool modloopend)" || { echo "joeymod: cannot build modloopend" >&2; exit 2; }
        "$modloopend" "$in" "$out"
        ;;
    ntp)
        modToNtp="$(joeyTool modToNtp)" || { echo "joeymod: cannot build modToNtp" >&2; exit 2; }
        "$modToNtp" "$in" "$out"
        ;;
    *)
        echo "joeymod: unknown output extension '.$ext' (expected .mod, .amod, or .ntp)" >&2
        exit 2
        ;;
esac

printf 'joeymod: %s -> %s (%d bytes)\n' "$in" "$out" "$(stat -c %s "$out")"
