summaryrefslogblamecommitdiff
path: root/.local/bin/cwall
blob: ad985a905b1e311cab48ae3aa40cddd9ef0c5c28 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15














                                                                          
                                                 

















                                                           









                                  







                                                       

















                                                                          

























                                                                






                                                        






                                        
#!/bin/sh

bgpid="${XDG_RUNTIME_DIR:-${TMPDIR:-/tmp}}/swaybg.pid"
bgroot="${XDG_DATA_HOME:-$HOME/.local/share}"
bgimg="${bgroot}/wallpaper"

die()
{
	printf "\033[31;1merr: %b\033[0m\n" "${1:-no args for die()}" 1>&2
	exit "${2:-1}"
}

usage()
{
	cat <<- EOF
	Usage: ${0##*/} [wallpaper.img|directory]
	A helper script for swaybg

	EOF
}

dep_check()
{
	# usage: cmd_check cmd_1 ...
	: "${1:?}"

	for dep; do
		command -v "$dep" 1>/dev/null ||
			die "${dep}: command not found" 127
	done

	unset dep
}

randimg()
{
	# usage: randbg dir
	: "${1:?}"
	maxattempts=10
	attempt=0

	img=
	while :; do
		img="$(find "$1" \
			-iname "*.avif" \
			-o -iname "*.heic" \
			-o -iname "*.heif" \
			-o -iname "*.jpeg" \
			-o -iname "*.jpg" \
			-o -iname "*.jxl" \
			-o -iname "*.png" \
			-o -iname "*.webp" | shuf -n1)"

		[ -z "$img" ] &&
			break;

		# make sure the file is an actual image
		case "$(file --brief --dereference --mime-type "$img")" in
		"image/"*)
			echo "$img"
			break;
			;;
		*)
			attempt=$((attempt + 1))
			[ "$attempt" -gt "$maxattempts" ] &&
				break;
		esac
	done
}

updatewall()
{
	: "${1:?}"

	rm -f "$bgimg"
	cp  "$1" "$bgimg"

	[ -s "$bgpid" ] &&
		kill "$(cat "$bgpid")"
	swaybg --mode fill --image "$bgimg" > /dev/null 2>&1 &
	echo $! > "$bgpid"
}

main()
{
	[ ! -r "$1" ] &&
		usage && exit 1;
	[ ! -d "$bgroot" ] &&
		mkdir -p "$bgroot"

	dep_check swaybg file

	case "$(file --brief --dereference --mime-type "$1")" in
	"image/"*)
		updatewall "$1"
		;;
	"inode/directory")
		img=$(randimg "$1")
		[ -z "$img" ] &&
			die "no image file in directory"

		updatewall "$img"
		;;
	*)
		die "invalid image file"
		;;
	esac
}

main "$@"