#!/usr/bin/env bash

# Script initialization
# Check if animated wallpapers exist, set env var if so
# Sleep for swww init to finish
init_static() {
    # On battery or missing wallpapers, just load a random image
    IMG=`find ~/.config/hypr/Wallpapers/static/ -type f | sort -R | tail -n1`
    echo $IMG >> /tmp/$USER-desktop-anim
    swww img $IMG
}

begin_randomizer() {
    while :; do
        sleep 3600
        switch_check `find ~/.config/hypr/Wallpapers/static/ -type f | sort -R | tail -n1`
    done
}

switch_check() {
    # Simply query what image is displayed and make sure we do not overwrite
    # it. This is more for animated wallpapers since it causes corruption
    CURRENT_FILE=`swww query | awk -F'/' '{print $NF}'`
    SELECTION=`echo $1 | awk -F'/' '{print $NF}'`

    if ! [ "$CURRENT_FILE" == "$SELECTION" ]; then
        # Update the file
        sed -i '2c'"$1" /tmp/$USER-desktop-anim
        # Set the background!
        swww img $1
    fi
}

init_static
begin_randomizer &