#!/usr/bin/env bash

normal=""
blurred=""
last=""
target=""

function update() {
    normal=$(find ~/.local/share/wallpaper/current -type f | head -n 1)
    blurred=$(find ~/.local/share/wallpaper/blurred -type f | head -n 1)

    [ -n "$normal" ] && [ -n "$blurred" ]
}

function apply() {
    swww img -n background "$1" --transition-type fade --transition-duration 0.5 > /dev/null 2> /dev/null
}

function isdesktop() {
    mapfile -t focused_lines < <(niri msg focused-window 2>/dev/null)

    [ "${#focused_lines[@]}" -le 1 ]
}

# single shot
[ -n "$1" ] && {
    update || exit 1

    if [ "$1" = "normal" ]; then
        target=$normal
    elif [ "$1" = "blurred" ]; then
        target=$blurred
    elif [ "$1" = "auto" ]; then
        if isdesktop; then
            target=$normal
        else
            target=$blurred
        fi
    else
        echo "Usage: $0 [normal|blurred|auto]"
        exit 1
    fi

    apply "$target"

    exit 0
}

while true; do
    # wait until wallpapers are ready
    update || {
        last="" # force apply when ready
        sleep 0.5
        continue
    }

    if isdesktop; then
        target="$normal"
    else
        target="$blurred"
    fi

    [ "$target" = "$last" ] || {
        apply "$target"
        last=$target
    }

    sleep 0.5
done
