#!/bin/bash
#+SPDX: MIT

## WE NEED SOME DEPENDENCIES
depcheck() {
	if ! command -v "$1" &> /dev/null ; then
		echo "Missing dependency $1"
		exit 1
	fi
}
depcheck fzf
depcheck swww
depcheck wal
depcheck foot

## Get wallpaper of choice.
# The single quoted argument of fzf is like that to preserve the variable
# The escaped $ is also there for the same reason
# The GSCRIPTS_WALLPAPERS variable is unqouted as globbing is wanted
# shellcheck disable=SC2016,SC2086
foot -W150x25 -a WallChooser -e bash -c "find ${GSCRIPTS_WALLPAPERS:-${HOME}/.local/share/backgrounds} -type f | fzf --keep-right --preview='img2sixel {} -w \$((FZF_PREVIEW_COLUMNS*8)) -h \$((FZF_PREVIEW_LINES*16)) --resampling=nearest' > /tmp/WallChooserChoice"
WALLPAPER="$(cat /tmp/WallChooserChoice)"

## If no choice leave immediately.
[[ -z $WALLPAPER ]] && exit

## First set the wallpaper
swww img "$WALLPAPER" &

## Now trigger pywal to update theme data to match
# -n as we don't need to set the wallpaper
wal -i "$WALLPAPER" -nq

## Now Set the "default" wallpaper symlink
ln -sf "$WALLPAPER" "${GSCRIPTS_WALLPAPERS:-${HOME}/.local/share/backgrounds}/default"
