#!/bin/bash
# Calls a script with "on" when a video device is opened and "off" when
# the last user closes it. Event-driven via inotify, no polling.
set -u

if [[ $# -lt 1 ]]; then
    echo "Usage: $0 LAMP_SCRIPT [VIDEO_DEVICE]" >&2
    exit 2
fi

lamp_script=$1
dev=${2:-/dev/video0}

if [[ ! -x $lamp_script ]]; then
    echo "Not an executable script: $lamp_script" >&2
    exit 2
fi
if [[ ! -e $dev ]]; then
    echo "Device does not exist: $dev" >&2
    exit 2
fi
command -v inotifywait >/dev/null || { echo "inotifywait missing (package inotify-tools)" >&2; exit 2; }

count=0
state=""

# video already open?
if command -v fuser >/dev/null; then
    pids=$(fuser "$dev" 2>/dev/null | wc -w)
    count=$pids
fi

apply() {
    local new=off
    ((count > 0)) && new=on
    if [[ $new != "$state" ]]; then
        state=$new
        "$lamp_script" "$state" || echo "Lamp script failed for '$state'" >&2
    fi
}

apply

wanted() { ((count > 0)) && echo on || echo off; }

# Debounce: after an event that would change the lamp state, wait until no
# further event arrives for $cooldown seconds before calling the script.
cooldown=0.5
pending=0

exec 3< <(inotifywait -m -q -e open -e close --format '%e' "$dev")

while true; do
    if ((pending)); then
        read -r -t "$cooldown" -u 3 ev; rc=$?
    else
        read -r -u 3 ev; rc=$?
    fi

    if ((rc > 128)); then
        # timeout: quiet period elapsed
        apply
        pending=0
        continue
    fi
    # EOF: inotifywait ended
    ((rc != 0)) && break

    case $ev in
        OPEN*)  ((count++)) ;;
        CLOSE*) if ((count > 0)); then ((count--)); fi ;;
    esac

    if [[ $(wanted) != "$state" ]]; then pending=1; else pending=0; fi
done

# inotifywait ended (device removed); exit nonzero so systemd restarts us
exit 1
