#!/usr/bin/env bash
# sdr-mic.sh — receive an ANALOG UHF wireless mic with an RTL-SDR dongle.
#
# Analog mics (old Shure ULX/SLX, Sennheiser EW100 G1-G3, etc.) are plain FM.
# rtl_fm demodulates FM and pipes raw audio to ffmpeg to save a WAV.
#
# Requires (one time, on WiFi):
#   brew install rtl-sdr gqrx
# Then plug the dongle in.
#
# Usage:
#   ./sdr-mic.sh 570.125               # tune to the mic's frequency (MHz)
#   ./sdr-mic.sh 570.125 /some/dir     # save elsewhere
set -euo pipefail

export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"
FREQ="${1:?usage: sdr-mic.sh <freq_MHz> [output_dir]}"

# --- parked-hardware checks: fail with a clear message instead of a cryptic error ---
if ! command -v rtl_fm >/dev/null 2>&1; then
  echo "PARKED: RTL-SDR software not installed. When the dongle arrives run:  brew install rtl-sdr" >&2
  exit 2
fi
if ! rtl_test -t 2>&1 | grep -q "Found [1-9]"; then
  echo "PARKED: no RTL-SDR dongle detected. Plug in the RTL-SDR USB dongle (~\$30) and try again." >&2
  exit 3
fi
OUT="${2:-$HOME/billo-wireless-audio/recordings}"
mkdir -p "$OUT"
STAMP=$(date +%Y%m%d-%H%M%S)
OUTFILE="$OUT/${STAMP}_uhf_${FREQ}MHz.wav"

echo "tuning ${FREQ} MHz (analog UHF mic) -> $OUTFILE"
echo "  (press Ctrl-C to stop)"

# rtl_fm: -M fm (FM demod), -f freq, -s/-r 48k, raw s16le to stdout.
# ffmpeg: wrap raw s16le into a WAV.
# Tune gain/ppm as needed: rtl_fm ... -g 42 -p 0
rtl_fm -M fm -f "${FREQ}M" -s 48k -r 48k - 2>/dev/null \
  | ffmpeg -hide_banner -y -f s16le -ar 48000 -ac 1 -i - \
      -c:a pcm_s16le "$OUTFILE"

echo "saved: $OUTFILE"
