#!/bin/bash

logfile="$HOME/.cache/booksyncd.log"
lockfile="$HOME/.cache/booksyncd.lock"
xbelfile="$HOME/.local/share/user-places.xbel"
gtkbookmarkfile="$HOME/.config/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
