#!/bin/sh
# ABOUTME: Switches every camera off at boot — the privacy default is "off until asked for".
# ABOUTME: Run by moonarch-camera.service; holds no state, the absence of state is the feature.

set -eu

PATH=/usr/bin:/bin
export PATH

# Cameras enumerate early, but a device behind a hub or dock can still be in flight. settle only
# waits for events already queued, so a very late arrival can stay on until the user switches it —
# accepted, since it is the same class of gap as plugging one in later.
if command -v udevadm >/dev/null 2>&1; then
    udevadm settle --timeout=10 || true
fi

# Reuse the enumeration rather than carrying a second copy of the descriptor walk.
LINES=$(/usr/bin/moonarch-camera-list || true)
[ -n "$LINES" ] || exit 0

printf '%s\n' "$LINES" | while IFS='|' read -r id hw label state kind; do
    [ -n "$id" ] || continue
    auth="/sys/bus/usb/devices/$id/authorized"
    if [ -f "$auth" ] && [ "$state" = "on" ]; then
        printf 0 > "$auth" || echo "Failed to switch off camera $id" >&2
    fi
done
