#!/usr/bin/bash

ensure_dir() {
	declare d

	for d in "$@"; do
		if ! [[ -d "$d" ]]; then
			if ! mkdir -p "$d"; then
				return $?
			fi
		fi
	done

	return 0
}

# Set XDG_RUNTIME_DIR
if ! [[ "$XDG_RUNTIME_DIR" ]]; then
	XDG_RUNTIME_DIR="/run/user/$UID"
fi

# Define some workdirs
bspwm_rundir="$XDG_RUNTIME_DIR/bspwm"
bspwm_statedir="$bspwm_rundir/state"

# Ensure the workdirs exist
ensure_dir "$bspwm_rundir" "$bspwm_statedir" || exit $?

case "$1" in
	(save)
		# Save state
		bspc query -T > "$bspwm_statedir/tree"
		bspc query -H > "$bspwm_statedir/hist"
		bspc query -S > "$bspwm_statedir/stack"
	;;

	(restore)
		# Restore state, if any
		[[ -f "$bspwm_statedir/tree" ]] && bspc restore -T "$bspwm_statedir/tree"
		[[ -f "$bspwm_statedir/hist" ]] && bspc restore -H "$bspwm_statedir/hist"
		[[ -f "$bspwm_statedir/stack" ]] && bspc restore -S "$bspwm_statedir/stack"
	;;
esac
