#!/usr/bin/env bash

usage() {
	echo "Usage: $(basename "$0") <directory> (mode)

    Picks a random file under <directory> (recursively) and sets it
    as the wallpaper on all monitors via 'hyprctl hyprpaper'.

    Example:
    $(basename "$0") ~/Pictures/Wallpapers contain"
    exit 1
}

if [[ $# -eq 0 ]]; then
	usage
fi

DIR="$1"
if [[ -n $2 ]]; then
	MODE="$2:"
	echo "Info: Mode set to '$MODE'"
else 
	MODE=""
fi

if [[ ! -d "$DIR" ]]; then
    echo "Error: '$DIR' is not a directory." >&2
    exit 2
fi

FILE=$(find "$DIR" -type f,l | shuf -n1)

if [[ -z "$FILE" ]]; then
    echo "Error: No files found in '$DIR'." >&2
    exit 3
fi

echo "Info: Chosen file '$FILE' from '$DIR'."

echo "Info: Preloading wallpaper"
hyprctl hyprpaper preload "$FILE"
echo "Info: Selecting wallpaper"
for monitor in $(hyprctl monitors | grep 'Monitor' | awk '{ print $2 }'); do
	echo  "	Info: Selecting wallpaper for: '$monitor'"
	hyprctl hyprpaper wallpaper "$monitor,$MODE$FILE"
done
echo "Info: Unloading unused wallpapers"
hyprctl hyprpaper unload all
