#!/usr/bin/env bash
# scripts/daemon/lesavka-uvc.sh - launch UVC control helper as a standalone service
set -euo pipefail

# Optional env file for runtime defaults (debug, width/fps, etc.). Explicit
# environment from a recovery shell wins so bench overrides are not masked.
load_uvc_env_defaults() {
    local env_file=/etc/lesavka/uvc.env
    [[ -r $env_file ]] || return 0
    local line key value
    while IFS= read -r line || [[ -n $line ]]; do
        [[ $line =~ ^[[:space:]]*# || -z $line ]] && continue
        [[ $line == *=* ]] || continue
        key=${line%%=*}
        value=${line#*=}
        [[ $key =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue
        [[ -z ${!key+x} ]] || continue
        export "$key=$value"
    done <"$env_file"
}

load_uvc_env_defaults

migrate_unsafe_uvc_defaults() {
    if [[ ${LESAVKA_UVC_BUFFER_COUNT:-} == "1" && -z ${LESAVKA_UVC_ALLOW_SINGLE_BUFFER:-} ]]; then
        echo "[lesavka-uvc] migrating legacy LESAVKA_UVC_BUFFER_COUNT=1 to 4; set LESAVKA_UVC_ALLOW_SINGLE_BUFFER=1 to keep the old behavior" >&2
        export LESAVKA_UVC_BUFFER_COUNT=4
    fi
    if [[ ${LESAVKA_UVC_QUEUE_PACING:-} == "1" && -z ${LESAVKA_UVC_ALLOW_QUEUE_PACING:-} ]]; then
        echo "[lesavka-uvc] migrating legacy LESAVKA_UVC_QUEUE_PACING=1 to 0; set LESAVKA_UVC_ALLOW_QUEUE_PACING=1 to keep the old behavior" >&2
        export LESAVKA_UVC_QUEUE_PACING=0
    fi
    export LESAVKA_UVC_BUFFER_COUNT=${LESAVKA_UVC_BUFFER_COUNT:-4}
    export LESAVKA_UVC_QUEUE_PACING=${LESAVKA_UVC_QUEUE_PACING:-0}
}

migrate_unsafe_uvc_defaults

resolve_default_uvc_dev() {
    local ctrl=""
    ctrl=$(ls /sys/class/udc 2>/dev/null | head -n1 || true)
    if [[ -n $ctrl ]]; then
        printf '/dev/v4l/by-path/platform-%s-video-index0\n' "$ctrl"
        return 0
    fi
    local candidate=""
    candidate=$(ls /dev/v4l/by-path/platform-*-video-index0 2>/dev/null | head -n1 || true)
    [[ -n $candidate ]] || return 1
    printf '%s\n' "$candidate"
}

wait_for_uvc_dev() {
    local dev="$1"
    for _ in {1..50}; do
        [[ -e $dev ]] && return 0
        sleep 0.1
    done
    return 1
}

if [[ -n ${LESAVKA_UVC_DEV:-} ]]; then
    DEV=${LESAVKA_UVC_DEV}
else
    DEV=$(resolve_default_uvc_dev || true)
fi

if [[ -z ${DEV:-} ]]; then
    echo "[lesavka-uvc] no gadget video_output node discovered; waiting for /dev/v4l/by-path/platform-*-video-index0 or set LESAVKA_UVC_DEV" >&2
    exit 1
fi

if ! wait_for_uvc_dev "$DEV"; then
    echo "[lesavka-uvc] gadget video_output node is still absent: $DEV" >&2
    exit 1
fi

exec /usr/local/bin/lesavka-uvc --device "$DEV"
