#!/usr/bin/env bash
# The companion servers record your microphone with `pw-record` (PipeWire). With PipeWire running
# this is the real pw-record; on a PulseAudio-only desktop, parec does the same (the default
# source, or $CW_MIC_SOURCE). Understands what the servers pass: --raw --rate --channels --format
# --latency and "-" (stdout).
self=$(realpath "$0")
real=""
IFS=: read -ra dirs <<< "$PATH"
for d in "${dirs[@]}"; do
    [ -x "$d/pw-record" ] && [ "$(realpath "$d/pw-record")" != "$self" ] && { real="$d/pw-record"; break; }
done
runtime="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
if [ -z "${CW_FORCE_PAREC:-}" ] && [ -n "$real" ] && [ -S "$runtime/${PIPEWIRE_REMOTE:-pipewire-0}" ]; then
    exec "$real" "$@"
fi
rate=48000 channels=1 format=s16le
while [ $# -gt 0 ]; do
    case "$1" in
        --rate) rate="$2"; shift ;;
        --rate=*) rate="${1#*=}" ;;
        --channels) channels="$2"; shift ;;
        --channels=*) channels="${1#*=}" ;;
        --format) format="$2"; shift ;;
        --format=*) format="${1#*=}" ;;
        --latency) shift ;;
    esac
    shift
done
case "$format" in s16) format=s16le ;; f32) format=float32le ;; s32) format=s32le ;; esac
exec parec ${CW_MIC_SOURCE:+-d "$CW_MIC_SOURCE"} --raw --format="$format" --rate="$rate" --channels="$channels" --latency-msec=20
