#!/bin/sh

STATUSFILE="/run/foxclient_update_status"

# Pick the first package server found in sources.list
PACKAGE_SERVER="$(
	cat /etc/apt/sources.list /etc/apt/sources.list.d/* 2>/dev/null |
	grep -oP '^deb (https?://[^ ]+)' |
	sed -e 's|.*//||' -e 's|/.*||' |
	head -n 1
)"

wait_for_package_server() {
    while ! /usr/lib/nagios/plugins/check_icmp -H "$PACKAGE_SERVER" -m 10 ; do
        sleep 10
    done
}

run_update() {
	# Start the update and wait for it to finish
	systemctl start --wait foxclient-update-job.service
}

wait_time="0"

while sleep "$wait_time"; do
   wait_for_package_server
   run_update
   if grep -q ^OK "$STATUSFILE" ; then
       wait_time=43200
   else
       wait_time=1800
   fi
done
