#!/bin/bash
# Installs the bundled manufacturer firmware package through /usr/bin/sysupgrade.
# Runs outside of the OTA's apt transaction (started by eurogard-rosp-update.service),
# because sysupgrade calls `dpkg -i`, which does not wait for the dpkg lock.
#
#   run          wait for the dpkg lock, install the payload, record the result
#   run --check  exit 0 if the payload still has to be installed, 1 if the device is current
set -u

CONF=/usr/share/eurogard/rosp-update/payload.conf
STATE_DIR=/app/eurogard/rosp-update
MARKER=${STATE_DIR}/pending
ATTEMPTS=${STATE_DIR}/attempts
RESULT=${STATE_DIR}/result.json
LOG=${STATE_DIR}/rosp-update.log
UPLOAD_COPY=/upload/eurogard-rosp-update.deb
MAX_ATTEMPTS=3
LOCK_TIMEOUT=900

# provides PAYLOAD_FILE, PAYLOAD_PKG, PAYLOAD_VERSION and optionally PAYLOAD_LEFTOVER
. "${CONF}" || exit 1

mkdir -p "${STATE_DIR}"

log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') $*" >> "${LOG}"
    logger -t eurogard-rosp-update "$*"
}

installed_version() {
    dpkg-query -W -f='${db:Status-Abbrev} ${Version}\n' "${PAYLOAD_PKG}" 2>/dev/null |
        awk '$1 == "ii" { print $2 }'
}

# The payload counts as installed only if the version matches AND the manufacturer's
# install.sh has finished: it removes its archive directory as its very last step.
payload_current() {
    local inst
    inst=$(installed_version)
    [ -n "${inst}" ] || return 1
    dpkg --compare-versions "${inst}" ge "${PAYLOAD_VERSION}" || return 1
    if [ -n "${PAYLOAD_LEFTOVER:-}" ] && [ -e "${PAYLOAD_LEFTOVER}" ]; then
        return 1
    fi
    return 0
}

json_escape() {
    printf '%s' "$1" | tr -d '"\\' | tr '\n\r\t' '   '
}

write_result() {
    local status=$1 rc=$2 detail=$3 tmp="${RESULT}.tmp"
    printf '{"status":"%s","package":"%s","target_version":"%s","installed_version":"%s","rc":%s,"attempt":%s,"reboot_required":"%s","detail":"%s","finished":"%s"}\n' \
        "${status}" "${PAYLOAD_PKG}" "${PAYLOAD_VERSION}" "$(installed_version)" "${rc}" \
        "${attempt:-0}" "$(renv get sys_need_reboot 2>/dev/null)" \
        "$(json_escape "${detail}")" "$(date '+%Y-%m-%d %H:%M:%S')" > "${tmp}" && mv -f "${tmp}" "${RESULT}"
}

# Failsafe of eurogard-web-files (>= 1.3.3, optional): before the installation it exports the configuration and switches the
# manufacturer's failback off (a half installed first boot must not end in a factory restore), `commit` switches it on again
failsafe() {
    [ -x "/usr/lib/eurogard/failsafe/$1" ] && "/usr/lib/eurogard/failsafe/$1" >> "${LOG}" 2>&1
    return 0
}

dpkg_locked() {
    fuser /var/lib/dpkg/lock /var/lib/dpkg/lock-frontend /var/cache/apt/archives/lock >/dev/null 2>&1
}

# Wait until the lock stays free for three consecutive seconds (apt may release it briefly
# between its steps).
wait_dpkg_lock() {
    local waited=0 free=0
    while [ "${free}" -lt 3 ]; do
        if dpkg_locked; then
            free=0
            [ "${waited}" -eq 0 ] && log "dpkg lock is held, waiting for the OTA transaction to finish"
        else
            free=$((free + 1))
        fi
        sleep 1
        waited=$((waited + 1))
        if [ "${waited}" -ge "${LOCK_TIMEOUT}" ]; then
            log "gave up waiting for the dpkg lock after ${LOCK_TIMEOUT}s"
            return 1
        fi
    done
    [ "${waited}" -gt 3 ] && log "dpkg lock released after ${waited}s"
    return 0
}

if [ "${1:-}" = "--check" ]; then
    payload_current && exit 1
    exit 0
fi

# called by the package postinst: replaces a stale result of an earlier run with a fresh state
if [ "${1:-}" = "--schedule" ]; then
    write_result "scheduled" 0 "update scheduled, waiting for the unit to start"
    exit 0
fi

log "start: target ${PAYLOAD_PKG} ${PAYLOAD_VERSION}, installed '$(installed_version)'"
write_result "waiting" 0 "waiting for apt to finish"

wait_dpkg_lock || { write_result "lock_timeout" 1 "dpkg lock was never released"; exit 1; }

if payload_current; then
    log "already current, nothing to do"
    rm -f "${MARKER}" "${ATTEMPTS}"
    write_result "current" 0 "already installed"
    failsafe commit
    exit 0
fi

attempt=$(( $(cat "${ATTEMPTS}" 2>/dev/null || echo 0) + 1 ))
if [ "${attempt}" -gt "${MAX_ATTEMPTS}" ]; then
    log "giving up after ${MAX_ATTEMPTS} attempts"
    rm -f "${MARKER}"
    write_result "gave_up" 1 "gave up after ${MAX_ATTEMPTS} attempts"
    failsafe commit
    exit 1
fi
echo "${attempt}" > "${ATTEMPTS}"
failsafe pre-firmware

# sysupgrade moves its argument away, so it gets a copy
mkdir -p /upload
rm -f "${UPLOAD_COPY}"
cp -f "${PAYLOAD_FILE}" "${UPLOAD_COPY}" || { log "cannot copy payload to /upload"; write_result "failed" 1 "cannot copy payload"; exit 1; }

log "attempt ${attempt}/${MAX_ATTEMPTS}: sysupgrade ${UPLOAD_COPY}"
write_result "running" 0 "installing the firmware package, attempt ${attempt}/${MAX_ATTEMPTS}"
sysupgrade "${UPLOAD_COPY}" >> "${LOG}" 2>&1
rc=$?
status=$(renv get sysupgrade_status 2>/dev/null)
reason=$(renv get sysupgrade_fail_reason 2>/dev/null)
log "sysupgrade finished: rc=${rc} sysupgrade_status='${status}' fail_reason='${reason}'"
rm -f "${UPLOAD_COPY}"

# /tmp is wiped on reboot, keep what the manufacturer's scripts leave behind
for f in /tmp/install_failure.log /tmp/deb_install.log /tmp/.updateinfo; do
    [ -f "${f}" ] && cp -f "${f}" "${STATE_DIR}/$(basename "${f}" | sed 's/^\.//')"
done

# sysupgrade exits 0 even when dpkg failed (it only sets sysupgrade_status=fail),
# so success means: exit code 0, status 'success' and the payload really installed.
if [ "${rc}" -eq 0 ] && [ "${status}" = "success" ] && payload_current; then
    log "payload installed, reboot required"
    rm -f "${MARKER}" "${ATTEMPTS}"
    write_result "success" "${rc}" "installed, reboot required"
    failsafe commit
    exit 0
fi

log "update failed, marker kept for a retry after the next boot"
write_result "failed" "${rc}" "sysupgrade_status=${status} reason=${reason}"
exit 1
