#!/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"
# The full CPU range comes from the kernel, not nproc: nproc reports the
# caller's affinity mask, which can be narrower than the machine (agent
# shells, cgroup limits) and silently excludes cores. On hybrid CPUs pin to
# the P-cores for the tuned latency (MPC_CPUSET=0-11 on a Core Ultra).
all_cpus=$(cat /sys/devices/system/cpu/online)
all_cpus=${all_cpus#0-}
export MAME_CPUSET="${MAME_CPUSET:-0-${all_cpus:-0}}"
# Raise MAME's audio threads above the emulation thread once it is up;
# without the realtime rlimit this is skipped with a warning.
raise_audio_threads()
{
    local mpid=
    for (( i = 0; i < 20; i++ )); do
        mpid=$(pgrep -x mpc | head -1) && [ -n "$mpid" ] && break
        sleep 1
    done
    [ -n "$mpid" ] || return 0
    if ! "$here/scripts/mpc-audio-thread-priority.sh"; then
        printf 'warning: could not raise audio thread priority (chrt); audio may underrun\n' >&2
    fi
    "$here/scripts/mpcpi-sampler-input" || true
}
# The full panel, maximized: the fast preset's LCD-only 1240x300 view is a
# diagnostic shape, not what a player wants to look at.
export MPC_VIEW_NAME="${MPC_VIEW_NAME:-Default Layout}"
export MPC_WINDOW_RESOLUTION="${MPC_WINDOW_RESOLUTION:-auto}"
export MPC_MAXIMIZE="${MPC_MAXIMIZE:-1}"
# The preset's event-driven panel UART ghosts button presses on the desktop -
# presses revert or are skipped. The accurate panel path (real panel CPU,
# stock UART timing) behaves; a desktop has the CPU headroom for it. The
# appliance is unaffected: it runs the panel HLE, a different path.
export MPC_PANEL_MODE="${MPC_PANEL_MODE:-accurate}"
export MPC_PANEL_TIMER_MODE="${MPC_PANEL_TIMER_MODE:-accurate}"
# Audio: rate-match the graph to the device (48 kHz on ACP-pinned drivers)
# and run the verified-clean 64-frame quantum. 32 frames is the untested
# opt-in.
# 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}"
"$here/scripts/run-mpc2000xl-fast.sh" \
    -pluginspath "$here/plugins" -plugin layout "$@" &
fast_pid=$!
raise_audio_threads
wait "$fast_pid"
