Fix bash trap variable scope bug in QR camera scanner

The cleanup_camera trap handler couldn't access local variables
(ffmpeg_pid, tmpdir) when triggered, causing "unbound variable"
errors with set -u. Fixed by using global paths with $$ suffix
that the trap can reference directly.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-02-13 08:19:52 -05:00
parent 5dadd584f0
commit dfc2d45cf5

25
setup
View File

@@ -216,15 +216,18 @@ scan_qr_camera() {
return 1
fi
local tmpdir="/tmp/usync_qr_$$"
local result_file="$tmpdir/result"
local ffmpeg_pid=""
# Use fixed paths (with PID) that cleanup can access without local vars
USYNC_QR_TMPDIR="/tmp/usync_qr_$$"
USYNC_QR_PIDFILE="/tmp/usync_qr_pid_$$"
mkdir -p "$tmpdir"
mkdir -p "$USYNC_QR_TMPDIR"
cleanup_camera() {
[[ -n "$ffmpeg_pid" ]] && kill "$ffmpeg_pid" 2>/dev/null || true
rm -rf "$tmpdir"
if [[ -f "/tmp/usync_qr_pid_$$" ]]; then
kill "$(cat "/tmp/usync_qr_pid_$$")" 2>/dev/null || true
rm -f "/tmp/usync_qr_pid_$$"
fi
rm -rf "/tmp/usync_qr_$$"
}
trap cleanup_camera RETURN EXIT
@@ -237,9 +240,9 @@ scan_qr_camera() {
ffmpeg -f v4l2 -video_size 640x480 -i /dev/video0 \
-vf "drawbox=x=iw/2-100:y=ih/2-100:w=200:h=200:color=green:t=3" \
-f sdl2 -window_title "Scan QR Code" - \
-vf "fps=2" -update 1 -q:v 2 "$tmpdir/frame.jpg" \
-vf "fps=2" -update 1 -q:v 2 "$USYNC_QR_TMPDIR/frame.jpg" \
-loglevel quiet 2>/dev/null &
ffmpeg_pid=$!
echo $! > "$USYNC_QR_PIDFILE"
sleep 1 # Let camera warm up
@@ -248,13 +251,13 @@ scan_qr_camera() {
sleep 0.5
# Check if ffmpeg died
if ! kill -0 "$ffmpeg_pid" 2>/dev/null; then
if [[ ! -f "$USYNC_QR_PIDFILE" ]] || ! kill -0 "$(cat "$USYNC_QR_PIDFILE")" 2>/dev/null; then
break
fi
if [[ -f "$tmpdir/frame.jpg" ]]; then
if [[ -f "$USYNC_QR_TMPDIR/frame.jpg" ]]; then
local result
result=$(zbarimg --raw -q "$tmpdir/frame.jpg" 2>/dev/null || true)
result=$(zbarimg --raw -q "$USYNC_QR_TMPDIR/frame.jpg" 2>/dev/null || true)
if [[ -n "$result" ]]; then
result=$(echo "$result" | tr -d ' \n\r' | tr '[:lower:]' '[:upper:]')