#!/usr/bin/env zsh

# bail out if not running under i3 or sway
if [[ ! -S ${I3SOCK} && ! -S ${SWAYSOCK} ]]; then
	echo "no running window manager detected, ${0:t} bailing out" >&2
	exit 0
fi

# record our own PID to avoid duplicate invocations
PIDFILE="/dev/shm/${0:t}.pid"

# check for already running script
if [[ -f ${PIDFILE} ]]; then
	for i in $(pidof -x ${0:t}); do
		if [[ ${i} -eq $(cat ${PIDFILE}) ]]; then
			echo "${0:t} already running!" >&2
			exit 1
		fi
	done
fi

# record current PID
echo ${$} > ${PIDFILE}

# main loop
while true; do

	# test for continued presence of a running window manager and bail if not found
	if [[ ! -S ${I3SOCK} && ! -S ${SWAYSOCK} ]]; then
		echo "window manager has stopped running, ${0:t} bailing out" >&2
		exit 0
	fi

	# build array of only type file present underneath my background directory
	bg=(~/bg/**/*(.))

	# if running i3, we need to set the background immediately, at random based on the array length
	if [[ -S ${I3SOCK} && ! ${I3SOCK} =~ "sway" ]]; then
		feh --no-fehbg --bg-max ${bg[$((RANDOM % $#bg + 1))]}
	fi

	# wait a bit
	sleep 10m

	# if running sway, select and set our new background at random based on the array length
	if [[ -S ${SWAYSOCK} ]]; then
		swaymsg -s ${SWAYSOCK} output '*' bg ${bg[$((RANDOM % $#bg + 1))]} fit
	fi

done

# exit with error since we should never get here
exit 1
