#!/usr/bin/env bash
set -euo pipefail
here=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
export MAME_BIN="$here/bin/mpc"
export MAME_ROM_DIR="$here/roms"
export MAME_RUNTIME_DIR="$here/runtime"
export MAME_CPUSET="${MAME_CPUSET:-0-$(( $(nproc) - 1 ))}"

virmidi_card=$(grep -l '^VirMIDI ' /proc/asound/card*/name 2>/dev/null | head -1 | grep -o 'card[0-9]*' | grep -o '[0-9]*' || true)
if [[ -z "$virmidi_card" ]]; then
    printf 'error: no snd-virmidi card found; run: sudo modprobe snd-virmidi\n' >&2
    exit 1
fi
midi_device="/dev/snd/midiC${virmidi_card}D0"
midi_port="Virtual Raw MIDI ${virmidi_card}-0"
if [[ ! -w "$midi_device" ]]; then
    printf 'error: %s is not writable; see the Maschine section of README.md\n' "$midi_device" >&2
    exit 1
fi
command -v python3 >/dev/null || { printf 'error: python3 is required for the hub\n' >&2; exit 1; }
python3 -c 'import PIL' 2>/dev/null || { printf 'error: the hub needs Pillow (python3-pil)\n' >&2; exit 1; }

hub_pid=
cleanup() {
    if [[ -n "$hub_pid" ]] && kill -0 "$hub_pid" 2>/dev/null; then
        kill "$hub_pid" 2>/dev/null || true
        wait "$hub_pid" 2>/dev/null || true
    fi
}
trap cleanup EXIT

printf 'Maschine hub: MIDI %s, emulator reads %s\n' "$midi_device" "$midi_port"
python3 "$here/maschine/maschine-hub.py" --midi "$midi_device" &
hub_pid=$!

# Turbo preset with the window back on: internal-pads input and the LCD
# export the hub reads, plus a visible LCD.
export MPC_VIDEO_MODE="${MPC_VIDEO_MODE:-opengl}"
export MPC_LCD_EXPORT_PATH="${MPC_LCD_EXPORT_PATH:-/dev/shm/mpc-lcd}"
"$here/scripts/run-mpc2000xl-turbo.sh" -midiin1 "$midi_port" "$@"
