#!/bin/bash
# jack-route-default — auto-connect JACK system captures to playbacks
# Run after JACK is started. Creates a 1:1 through-patch for direct monitoring.

jack_wait -w

# Get available ports
captures=$(jack_lsp -c system | grep capture || true)
playbacks=$(jack_lsp -c system | grep playback || true)

if [ -z "$captures" ] || [ -z "$playbacks" ]; then
    echo "No system capture or playback ports found. Is JACK running?"
    echo "Check: jack_lsp -c system"
    exit 1
fi

# Route capture -> playback in pairs
# Assumes matching channel counts; pairs capture_1->playback_1, etc.
MAX_CHANNELS=18

for i in $(seq 1 $MAX_CHANNELS); do
    CAP_PORT="system:capture_${i}"
    PB_PORT="system:playback_${i}"

    if jack_lsp -c system | grep -q "^${CAP_PORT}$" && \
       jack_lsp -c system | grep -q "^${PB_PORT}$"; then
        jack_connect "$CAP_PORT" "$PB_PORT" 2>/dev/null && \
            echo "  Connected: $CAP_PORT -> $PB_PORT" || \
            echo "  Already connected: $CAP_PORT -> $PB_PORT"
    fi
done

# Optional: start a2jmidid for MIDI bridging
if command -v a2j_control &> /dev/null; then
    if ! pgrep -x a2jmidid > /dev/null; then
        a2j_control start 2>/dev/null && echo "  MIDI bridge (a2jmidid) started"
    fi
fi

echo "Routing complete."
