#!/bin/sh

# 15m
UPDATES_SLEEP=900
UPDATES_VM=`qvm-get-updatevm`

QREXEC_CLIENT=/usr/lib/qubes/qrexec_client

if [ -z "$UPDATES_VM" ]; then
    echo "UpdateVM not set, exiting!" >&2
    exit 1
fi

echo "Waiting for UpdateVM to be started"
# Intentionally used xl domid here to check if domain is running (in case of
# eg. stale qrexec socket)
while ! [ -S /var/run/qubes/qrexec.`xl domid "$UPDATES_VM" 2>/dev/null` ]; do
    sleep 1
done

(
# Allow only one instance
flock --nonblock -s 200 || exit 1
while true; do
    qvm-sync-dom0-clock

    sleep $UPDATES_SLEEP
done


) 200> /var/run/qubes/clock-watch-lock