#!/usr/bin/bash
# Present exercises next to a simple timer.
SOUND="/usr/share/sounds/freedesktop/stereo/alarm-clock-elapsed.oga"
THINK=30
PAIR=30
PATTERN="*.pdf"
PEACLOCK_CONF="$(mktemp /tmp/peaclock-XXX.conf)"
PEACLOCK_ARGS="-u $PEACLOCK_CONF"

# Create a temporary peaclock timer config
write_timer_conf() {
	{
		echo "set seconds on"
		echo "timer ${1}s"
		echo "mode timer"
		echo "timer start"
	} > "$PEACLOCK_CONF"
}

for f in "$1"/$PATTERN; do
	xdg-open "$f" &

	write_timer_conf $THINK
	# Explicit word expansion of PEACLOCK_ARGS is safe because
	# PEACLOCK_CONF does not contain spaces
	# shellcheck disable=SC2086
	timeout --foreground $THINK peaclock $PEACLOCK_ARGS
	ffplay -autoexit -nodisp "$SOUND" 2>/dev/null

	write_timer_conf $PAIR
	# shellcheck disable=SC2086
	timeout --foreground $PAIR peaclock $PEACLOCK_ARGS
	ffplay -autoexit -nodisp "$SOUND" 2>/dev/null

	reset
	read -rp "next>"
	# Word splitting to expand all PIDs
	# shellcheck disable=SC2046
	kill $(jobs -p)
done
