#!/bin/sh
# ~/.local/bin/lock — blur-lock screen (robust version)
# deps: scrot, imagemagick, i3lock

# fall back to plain color if anything breaks, never leave the screen unlocked
abort() {
    echo "lock: $1, using plain color" >&2
    exec i3lock -n -c 1d2021
}

command -v scrot   >/dev/null 2>&1 || abort "scrot missing"
command -v convert >/dev/null 2>&1 || abort "imagemagick missing"
command -v i3lock  >/dev/null 2>&1 || {
    echo "i3lock missing — cannot lock" >&2
    exit 1
}

SHOT="/tmp/lockshot.png"
BLUR="/tmp/lockblur.png"
rm -f "$SHOT" "$BLUR"

# 1. grab the screen — test that the file is actually a real, non-empty PNG
if ! scrot "$SHOT" || [ ! -s "$SHOT" ]; then
    abort "screenshot failed"
fi

# 2. blur + dim
#    -level-based dimming avoids %[fx:] syntax differences between IM versions
if ! convert "$SHOT" \
        -filter Gaussian -blur 0x10 \
        -fill black -colorize 45% \
        "$BLUR" 2>/tmp/lockerr.txt; then
    cat /tmp/lockerr.txt >&2
    abort "convert failed"
fi

[ -s "$BLUR" ] || abort "blur output empty"
rm -f /tmp/lockerr.txt

# 3. lock with the blurred image
exec i3lock -n -i "$BLUR"
