#!/bin/sh
# Sample backlight state so an unattended dim/restore cycle can be reconstructed.
# A long gap between samples means the machine was suspended, which is the window
# where DDC writes are suspected to be lost, so that case is sampled densely.
LOG=$HOME/.local/state/backlight-probe.log

read_all() {
    out=
    for p in /sys/class/backlight/*; do
        [ -e "$p" ] || continue
        out="$out ${p##*/}=$(cat "$p/brightness" 2>/dev/null)/$(timeout 2 cat "$p/actual_brightness" 2>/dev/null || echo ERR)"
    done
    printf '%s' "$out"
}

cached() {
    out=
    for p in /sys/class/backlight/*; do
        [ -e "$p" ] || continue
        out="$out ${p##*/}=$(cat "$p/brightness" 2>/dev/null)"
    done
    printf '%s' "$out"
}

prev=
last=$(date +%s)
printf '%s START%s\n' "$(date '+%F %T')" "$(read_all)" >>"$LOG"

while :; do
    now=$(date +%s); gap=$((now - last)); last=$now
    cur=$(cached)

    if [ "$gap" -gt 10 ]; then
        printf '%s GAP %ss (suspend/resume)\n' "$(date '+%F %T')" "$gap" >>"$LOG"
        i=0
        while [ "$i" -lt 40 ]; do
            printf '%s   +%02ds%s\n' "$(date '+%F %T')" "$i" "$(read_all)" >>"$LOG"
            i=$((i + 1)); sleep 1
        done
        prev=
    elif [ "$cur" != "$prev" ]; then
        printf '%s CHANGE%s\n' "$(date '+%F %T')" "$(read_all)" >>"$LOG"
        prev=$cur
    fi
    sleep 2
done
