#!/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"
all_cpus=$(cat /sys/devices/system/cpu/online)
all_cpus=${all_cpus#0-}
export MAME_CPUSET="${MAME_CPUSET:-0-${all_cpus:-0}}"
# ACP-off is OPT-IN. Measured on this workstation (Meteor Lake HDA,
# SN6140): with ACP disabled the emulator never creates its PipeWire
# nodes at all and stalls at ~5% CPU, old and new binaries alike;
# restoring ACP brought it straight back. Auto-installing it turned a
# working machine into a black window, so it ships behind a flag.
if [ -n "${MPCPI_DISABLE_ACP:-}" ]; then
    "$here/scripts/mpcpi-audio-setup"
fi
export PIPEWIRE_RATE_HZ="${PIPEWIRE_RATE_HZ:-48000}"
export MPC_PIPEWIRE_FRAMES="${MPC_PIPEWIRE_FRAMES:-64}"

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" "$@" &
fast_pid=$!
# The audio-thread starvation fix applies here too.
if "$here/scripts/mpc-audio-thread-priority.sh"; then :; else
    printf 'warning: could not raise audio thread priority (chrt); audio may underrun\n' >&2
fi
"$here/scripts/mpcpi-sampler-input" || true
trap '"$here/scripts/mpcpi-sampler-input" --stop 2>/dev/null || true' EXIT INT TERM
wait "$fast_pid"
