#!/bin/sh

# This hook does 2 things whenever you save the data files:
#
# 1. Make a commit if the calcurse directories contain a Git repository.
# 2. Synchronize with a CalDAV server if calcurse-caldav is configured.

data_dir="${XDG_DATA_HOME:-$HOME/.local/share}/calcurse"
config_dir="${XDG_CONFIG_HOME:-$HOME/.config}/calcurse"

# Do not do anything when synchronizing with a CalDAV server.
[ -f "$data_dir/caldav/lock" ] && exit

# If the directory is under version control, create a Git commit.
commit_dir() {
	cd "$1" >/dev/null 2>&1 || return
	shift
	if [ -d .git ] && command -v git >/dev/null; then
		git add "$@"
		if ! git diff-index --quiet --cached HEAD; then
			git commit -m "Automatic commit by the post-save hook"
		fi
	fi
}

commit_dir "$data_dir" apts todo
commit_dir "$config_dir" conf keys

# Optionally run the CalDAV synchronization script in the background.
cd "$data_dir" || exit
if [ -d caldav ] && command -v calcurse-caldav >/dev/null; then
	(
		date="$(date +'%b %d %H:%M:%S')"
		echo "$date Running calcurse-caldav from the post-save hook..."
		calcurse-caldav --init keep-remote
	) >> caldav/log 2>&1 &
	notify-send -u low -i "${XDG_DATA_HOME:-$HOME/.local/share}/icons/notifications/calendar.png" 'Calendar' 'Calendar synchronized with CalDAV server'
fi
