#!/bin/sh
# Runs at every boot (eurogard-failsafe-boot.service), before the update units. Never fails.
#   1. an interrupted dpkg (power loss while packages were installed) is repaired with `dpkg --configure -a`;
#      a half installed update bundle that cannot be configured is removed (it has to be uploaded again)
#   2. leftovers of an update that was cut off: verify_flag=skip (set by eurogard_offline_update_check, its reset timer
#      does not survive a reboot) and the uploaded file in /upload
#   3. if the failback was switched off for an update and the installation does not get done, it is switched on again
#      after three boots (the manufacturer's logic then takes over)
. "$(dirname "$0")/common.sh"

log "boot: start (failback flag: $(failback_value))"

# --- 1. dpkg
if ! dpkg_clean; then
    if fuser /var/lib/dpkg/lock /var/lib/dpkg/lock-frontend > /dev/null 2>&1; then
        log "boot: dpkg is busy, not repairing now"
    else
        log "boot: dpkg is not clean: $(dpkg --audit 2>&1 | tr '\n' ' ' | head -c 400) updates: $(ls /var/lib/dpkg/updates 2> /dev/null | tr '\n' ' ')"
        DEBIAN_FRONTEND=noninteractive timeout 840 dpkg --configure -a --force-confold < /dev/null >> "${STATE}/dpkg-repair.log" 2>&1
        log "boot: dpkg --configure -a finished (rc $?)"
        if ! dpkg_clean; then
            # not configurable: nothing to configure from, e.g. the unpacking of the bundle was cut off
            for pkg in eurogard-offline-update; do
                st=$(dpkg-query -W -f='${db:Status-Abbrev}' "${pkg}" 2> /dev/null | tr -d ' ')
                case "${st}" in
                    ?H*|?U*|??R)
                        log "boot: removing ${pkg} (status ${st}), the update file has to be uploaded again"
                        dpkg --remove --force-remove-reinstreq "${pkg}" >> "${STATE}/dpkg-repair.log" 2>&1
                        ;;
                esac
            done
            rm -rf /var/lib/dpkg/updates/* 2> /dev/null
            dpkg_clean && log "boot: dpkg is clean now" || log "boot: dpkg is still not clean: $(dpkg --audit 2>&1 | tr '\n' ' ' | head -c 400)"
        else
            log "boot: dpkg is clean now"
        fi
    fi
fi

# --- 2. leftovers
renv del verify_flag > /dev/null 2>&1
if ! update_pending && ! systemctl is-active --quiet eurogard-ota-update.service 2> /dev/null; then
    rm -f /upload/tempfile /upload/temp.deb
fi

# the offline copy of the Node-RED image (hard link of the bundle image) is only kept until the staging is done
if ! update_pending && [ ! -e /app/eurogard/nodered/pending-stage ] && [ -e /usr/share/eurogard/nodered/image.tar ]; then
    rm -f /usr/share/eurogard/nodered/image.tar
    log "boot: removed the leftover Node-RED image archive"
fi

# --- 3. failback
if [ -e "${PENDING}" ]; then
    n=$(cat "${BOOTS}" 2> /dev/null || echo 0)
    n=$((n + 1))
    echo "${n}" > "${BOOTS}"
    log "boot: ${n}. boot since the failback was switched off"
    if [ "${n}" -ge 4 ]; then
        failback_restore "four boots without a finished installation"
    fi
fi

log "boot: done"
exit 0
