#!/bin/sh

dir="$HOME/Pictures/Wallpapers/"
sway_socket=$(find "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}" -type s -prune -name 'sway-ipc.*.sock' 2>/dev/null)

if [ -S "$sway_socket" ]; then
	outputs=$(swaymsg -r -t get_outputs | jq -r .[].name)
else
	outputs=$(wlr-randr --json | jq -r .[].name)
fi

num_outputs=$(echo "$outputs" | wc -l)

wallpapers=$(find "$dir" -type f -o -type l \
	-name "*.png" \
	-o -name "*.jpg" \
	-o -name "*.jpeg" \
	-o -name "*.webp" \
{% if wallpaper_engine == 'swww' %}
	-o -name "*.gif" \
{% endif %}
	-o -name "*.PNG" \
	-o -name "*.JPG" \
	-o -name "*.JPEG" \
	-o -name "*.WEBP" | \
	shuf -n "$num_outputs")

num_wallpapers=$(echo "$wallpapers" | wc -l)

{% set get_output_cmd = '$(echo "$outputs" | sed -n "${i}p")' -%}
{% set get_wallpaper_cmd = '$(echo "$wallpapers" | sed -n "$([ "$i" -ge "$num_wallpapers" ] && printf "%d" "$num_wallpapers" || printf "%d" "$i")p")' -%}
{% if wallpaper_engine == 'swaybg' %}
args=""
for i in $(seq 1 "$num_outputs"); do
	args="${args} --output "{{ get_output_cmd }}" --image "{{ get_wallpaper_cmd }}" --mode fill"
done
exec swaybg ${args}
{% elif wallpaper_engine == 'swww' %}
for i in $(seq 1 "$num_outputs"); do
	swww img \
		--transition-type random \
		--transition-step 10 \
		--filter Lanczos3 \
		--outputs "{{ get_output_cmd }}" \
		"{{ get_wallpaper_cmd }}"
done
{% endif %}
