#!/bin/bash
# setup-lib.sh — shared setup helpers. SOURCED by the other setup scripts, not run.
#
# Robust against the classic FABRIC first-boot failure: cloud-init / unattended
# upgrades holding the apt lock. wait_for_apt() waits it out; apt_retry() retries.

wait_for_apt() {
    echo "### PROGRESS: [setup] waiting for cloud-init / apt locks..."
    sudo cloud-init status --wait >/dev/null 2>&1 || true
    for _ in $(seq 1 120); do   # up to ~20 min for the boot apt-daily / unattended-upgrades
        if sudo fuser /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock \
                       /var/lib/apt/lists/lock /var/cache/apt/archives/lock \
                       >/dev/null 2>&1 \
           || pgrep -x apt-get >/dev/null 2>&1 \
           || pgrep -x unattended-upgr >/dev/null 2>&1 \
           || pgrep -x dpkg >/dev/null 2>&1; then
            sleep 10
        else
            return 0
        fi
    done
    echo "### PROGRESS: [setup] WARNING — apt still busy after wait"
}

apt_retry() {  # apt_retry <apt-get args...>
    for attempt in 1 2 3 4 5; do
        if sudo DEBIAN_FRONTEND=noninteractive sudo apt-get "$@"; then
            return 0
        fi
        echo "### PROGRESS: [setup] apt attempt $attempt failed; retrying..."
        sleep 10
        wait_for_apt
    done
    return 1
}
