#!/usr/bin/env bash
set -eo pipefail

if [ -z "${WALLPAPER_DIR}" ]; then
    WALLPAPER_DIR="${HOME}/wallpapers"
fi

if ! [ -d "$WALLPAPER_DIR" ]; then
    echo "Wallpaper dir is not a directory"
    exit 1
fi

wallpaper_path=$(find "$WALLPAPER_DIR" -mindepth 1 | sort -R | tail -n 1)

if [ -z "$wallpaper_path" ]; then
    echo "Unable to find wallpaper"
    exit 1
fi

if ! command -v hyprpaper &> /dev/null; then
    echo "Could not find hyprpaper command"
    exit 1
fi

echo "setting $wallpaper_path as wallpaper"
hyprctl hyprpaper unload all
hyprctl hyprpaper preload "$wallpaper_path"

for monitor in $(hyprctl monitors | grep 'Monitor' | awk '{ print $2 }'); do
    hyprctl hyprpaper wallpaper "$monitor,$wallpaper_path"
done