#!/bin/sh # Run a supervised test while the stock microphone service is temporarily paused. set -eu cd "$(dirname "$0")" mode=${1:-ptt} case "$mode" in ptt|enroll|wake) ;; *) echo "Usage: $0 [ptt|enroll|wake] [client flags]" >&2; exit 2 ;; esac if [ "$#" -gt 0 ]; then shift; fi umask 077 exec 9>/tmp/alice-backend-mic.lock if ! flock -n 9; then echo 'A station microphone test is already running.' >&2 exit 1 fi exec 3<&0 if [ "$mode" != enroll ]; then DEVICE_TOKEN=$(cat device-token) export DEVICE_TOKEN fi set -f owners=$(fuser /dev/snd/pcmC0D1c 2>/dev/null || true) launcher= guard= client= mic_owned_by_stock() { mic_pid=$(fuser /dev/snd/pcmC0D1c 2>/dev/null | tr -d '[:space:]' || true) case "$mic_pid" in ''|*[!0-9]*) return 1 ;; esac [ "$(tr '\0' ' ' < "/proc/$mic_pid/cmdline" 2>/dev/null)" = '/system/vendor/quasar/maind --platformd ' ] } restore() { if [ -n "$guard" ]; then kill "$guard" 2>/dev/null || true; fi if [ -n "$client" ]; then kill -TERM "$client" 2>/dev/null || true wait "$client" 2>/dev/null || true fi if [ -n "$launcher" ] && [ "$(readlink "/proc/$launcher/exe")" = /system/vendor/quasar/quasar_launcher2 ]; then kill -CONT "$launcher" 2>/dev/null || true for second in 1 2 3 4 5 6 7 8; do if mic_owned_by_stock; then return; fi sleep 1 done echo 'Restarting stock Quasar to restore microphone ownership.' >&2 /system/vendor/quasar/q restart 9>&- fi } trap restore EXIT trap 'exit 130' HUP INT TERM if [ -n "$owners" ]; then platform=$(printf '%s' "$owners" | tr -d '[:space:]') case "$platform" in ''|*[!0-9]*) echo "Unexpected microphone owner" >&2; exit 1 ;; esac if [ "$(tr '\0' ' ' < "/proc/$platform/cmdline")" != '/system/vendor/quasar/maind --platformd ' ]; then echo 'Microphone is busy.' >&2 exit 1 fi launcher=$(awk '$1 == "PPid:" { print $2 }' "/proc/$platform/status") if [ "$(readlink "/proc/$launcher/exe")" != /system/vendor/quasar/quasar_launcher2 ]; then launcher= echo 'Unexpected parent process.' >&2 exit 1 fi fi # A finite test and detached fallback restore the stock launcher even after SSH loss. lease=90 owner=$$ started=$(awk '{print $22}' "/proc/$owner/stat") nohup sh -c ' sleep "$1" if [ "$(awk "{print \$22}" "/proc/$2/stat" 2>/dev/null)" = "$3" ]; then kill -TERM "$2" 2>/dev/null || true fi if [ -n "$4" ] && [ "$(readlink "/proc/$4/exe")" = /system/vendor/quasar/quasar_launcher2 ]; then kill -CONT "$4" 2>/dev/null || true fi ' sh "$lease" "$owner" "$started" "$launcher" /dev/null 2>&1 9>&- & guard=$! if [ -n "$launcher" ]; then kill -STOP "$launcher" kill -TERM "$platform" for second in 1 2 3; do if ! fuser /dev/snd/pcmC0D1c >/dev/null 2>&1; then break; fi sleep 1 done if fuser /dev/snd/pcmC0D1c >/dev/null 2>&1; then echo 'The stock service kept the microphone.' >&2 exit 1 fi fi ./alice-station -mode "$mode" "$@" <&3 9>&- & client=$! wait "$client" client=