#!/bin/bash
# Renradio Broadcast SE -- start the JACK server with the dummy driver (a clock, no sound card).
# Realtime scheduling is tried first; when the system does not allow it, jackd starts without.
CFG=/opt/renradio/config/renradio.json
read -r RATE PERIOD RT < <(/usr/bin/python3 - <<'PY'
import json
try:
    e = json.load(open("/opt/renradio/config/renradio.json")).get("engine", {})
except Exception:
    e = {}
print(e.get("sample_rate", 44100), e.get("jack_period", 2048), 1 if e.get("jack_realtime", True) else 0)
PY
)
export JACK_NO_AUDIO_RESERVATION=1 HOME=/opt/renradio/data
DRV=(-d dummy -r "${RATE:-44100}" -p "${PERIOD:-2048}" -C 2 -P 2)
if [[ "${RT:-1}" == "1" ]]; then
  /usr/bin/jackd -R -P 60 "${DRV[@]}" &
  PID=$!
  sleep 3
  if kill -0 "$PID" 2>/dev/null; then
    trap 'kill $PID 2>/dev/null' TERM INT
    wait "$PID"; exit $?
  fi
  echo "jackd could not start with realtime priority; starting without" >&2
fi
exec /usr/bin/jackd -r "${DRV[@]}"
