#!/bin/bash

if [ -z "$XDG_CACHE_HOME" ] ; then
	XDG_CACHE_HOME="$HOME/.cache/"
fi

if [ -z "$XDG_CONFIG_HOME" ] ; then
	XDG_CONFIG_HOME="$HOME/.config/"
fi

if [ -z "$XDG_DATA_HOME" ] ; then
	XDG_DATA_HOME="$HOME/.local/share/"
fi

logfile="$XDG_CACHE_HOME/booksyncd.log"
lockfile="$XDG_CACHE_HOME/booksyncd.lock"
xbelfile="$XDG_DATA_HOME/user-places.xbel"
gtkbookmarkfile="$XDG_CONFIG_HOME/gtk-3.0/bookmarks"

updatefile="/etc/booksync_updates.py"

exec 200>>"$lockfile"
flock -x -w 1 200 || exit 100

exec 100>"$logfile"

while [ ! -f "$xbelfile" ] ; do
	sleep 1
done

mkdir -p "$(dirname "$gtkbookmarkfile")"
touch "$gtkbookmarkfile"

quit() {
	echo "quit: $?" >&100
	flock -u 200
	touch "$xbelfile" >&100
	exit
}

trap quit EXIT

while true; do
	echo "sync at $(date "+%Y-%m-%d %H:%M:%S")" >&100
	booksync.py --set-xbel-path "$xbelfile" --apply-updates-from "$updatefile" --set-gtk-path "$gtkbookmarkfile"  >&100 2>&100 || quit
	echo "" >&100
	echo "Waiting for change in file at $(date "+%Y-%m-%d %H:%M:%S")" >&100
	inotifywait -e close_write "$xbelfile" >&100
	echo "" >&100
	echo "" >&100
done
