#
# These things are run when a Waybox Wayland session is started.
# Copy to $XDG_CONFIG_HOME/waybox/autostart to customize.
#

#
# Change from Openbox: the desktop environment's config tools should begin
# through autostart elements (e.g. /etc/xdg/autostart); there's no need to
# specify them here.
#


# Update the DBus environment
dbus-update-activation-environment --systemd WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE

# Start a dock
cairo-dock &

# Start a panel
(waybar || yambar) &

# Start a notification daemon
mako &

# Load a random wallpaper
get_random_wallpaper()
{
    oldifs=$IFS
    IFS=:
    data_dirs=${XDG_DATA_DIRS:-${datadir:-/usr/share}}:${XDG_DATA_HOME:-~/.local/share}
    for data_dir in $data_dirs;do
        IFS=$oldifs
        wpdir="$data_dir/wallpapers"
        test -d "$wpdir" && \
            find $wpdir -name '*.jpg' -o -name '*.png' -o -name '*.svg'
    done | (shuf -n 1 || tail -n 1)
}

load_wallpaper() {
    uses_wayland_info=0
    if (which hyprpaper && which socat && (test "$uses_wayland_info" = "0" || which wayland-info)) >/dev/null 2>&1; then
        hyprpaper &
        HYPRPAPER_SOCKET="${XDG_RUNTIME_DIR:-"/run/user/$(id -u)"}"/hypr/.hyprpaper.sock
        # Change the wallpaper every hour
        while test -S "$HYPRPAPER_SOCKET"; do
            if test "$uses_wayland_info" != "0";
            then
                current_output=$(wayland-info -i wl_output | \
                    grep 'name:' | tail -n 1 | cut -d : -f 2 | tr -d ' ')
            fi
            random_wallpaper="$(get_random_wallpaper)"
            for cmd in "preload $random_wallpaper" \
                "wallpaper $current_output,$random_wallpaper" \
                'unload all';
            do
                printf "$cmd" | socat UNIX-CONNECT:"$HYPRPAPER_SOCKET" -
            done
            [ $? -ne 0 ] && rm -f $HYPRPAPER_SOCKET
            sleep 60m
        done
    elif which swaybg >/dev/null 2>&1; then
        get_random_wallpaper | xargs swaybg -c '#303030' -m fill -i &
    elif which wpaperd >/dev/null 2>&1; then
        wpaperd &
    fi
}

load_wallpaper &

# vim: ft=sh
