#!/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

if [ "$#" -eq 1 ]; then
    wallpaper_path="$1"
    ext=$(file --extension "$wallpaper_path" | cut -d" " -f2)
    if ! [ "$ext" == "png" ]; then
        echo "$wallpaper_path is an invalid wallpaper"
    fi
else
    wallpaper_path=$(find "$WALLPAPER_DIR" -mindepth 1 | grep png| grep -v current| sort -R | tail -n 1)
fi


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

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

if command -v wal &> /dev/null; then
    wal -i "$wallpaper_path"
fi

unlink "$WALLPAPER_DIR/current.png" || true
ln -s "$wallpaper_path" "$WALLPAPER_DIR/current.png"

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