#!/bin/sh
# pomelo-apt-config: one-time package lists (see build-apt-config.sh)
n=0; while [ $n -lt 180 ]; do grep -q nameserver /etc/resolv.conf 2>/dev/null && break; sleep 2; n=$((n + 2)); done
ls /var/lib/apt/lists/*Packages* >/dev/null 2>&1 && exit 0
# Not while the desktop is starting: on a one-CPU or emulated (no KVM) machine `apt-get update` took the CPU from udev coldplug and the
# compositor for 1-2 minutes ("starting the desktop" for ever).  Wait until the panel is up (boot stage session-up, or the login screen
# for at most 10 minutes), then 20 s more, and run at the lowest priority.
n=0; while [ $n -lt 600 ]; do grep -q session-up /proc/pomelo_boot_times 2>/dev/null && break; sleep 3; n=$((n + 3)); done
sleep 20
# Bounded: a network that hands out an address but reaches nothing (offline VM, captive portal, firewall) made `apt-get update` hang for
# many minutes while holding the apt lock, so `apt install` failed.  20 s per connection, 2 tries, 150 s per run, 3 runs at most.
n=0
while [ $n -lt 3 ]; do
  timeout 150 nice -n 19 /usr/bin/apt-get -q -o Acquire::http::Timeout=20 -o Acquire::https::Timeout=20 -o Acquire::Retries=1 update >> /var/log/pomelo-apt-update.log 2>&1 && exit 0
  ls /var/lib/apt/lists/*Packages* >/dev/null 2>&1 && exit 0
  n=$((n + 1)); sleep 30
done
exit 1
