#!/bin/sh
# Update notice: tells the user after the reboot whether an update completed, or that it has to be started again.
#
#   notice start --to VERSION --mode ota|offline   an update to eurogardcore2 VERSION begins (called by eurogard_ota_update
#                                                  and the offline update runner, before anything is installed)
#   notice status                                  decide what the web UI shows, publish it as usi values
#                                                  eurogard_version.noticeState = none | running | success | incomplete
#                                                  (+ noticeFrom, noticeTo, noticeMode, noticeReason), print them as one line
#   notice ack                                     the user has seen the message: forget it (shown once)
#
# The record lives in /data (survives the restore of a backup, the failback of RobustOS Pro 2.4.x brings the OLD version
# back and the user has to learn that the update did not happen).
#   none        no record, nothing to tell, or the router was not rebooted since the update started (the update dialog
#               of the version page still shows its own result)
#   running     an update unit or dpkg is still busy after the reboot, ask again later
#   success     eurogardcore2 has the target version (or newer) and dpkg is clean
#   incomplete  anything else: reason "version" (old version still installed) or "dpkg" (installation incomplete)
# A record from before a factory restore, or older than 14 days, is dropped silently.
. "$(dirname "$0")/common.sh"

NOTICE=${STATE}/update-notice
BOOT_ID_FILE=${EG_FAILSAFE_BOOT_ID:-/proc/sys/kernel/random/boot_id}
RESTORE_CMD=${OVERLAY}/.rbt-system-mgmt-restore-cmd
MAX_AGE=${EG_FAILSAFE_NOTICE_MAX_AGE:-1209600}
RETRY_AGE=${EG_FAILSAFE_NOTICE_RETRY_AGE:-21600}      # a retry of an update is not older than this (6 h)

core_version() {
    dpkg-query -W -f='${Version}' eurogardcore2 2> /dev/null
}

field() {
    sed -n "s/^$1=//p" "${NOTICE}" 2> /dev/null | head -n 1 | tr -cd 'A-Za-z0-9._+~:-'
}

publish() {
    # $1 state, $2 from, $3 to, $4 mode, $5 reason
    if command -v usi > /dev/null 2>&1; then
        usi set eurogard_version.noticeState "$1" > /dev/null 2>&1
        usi set eurogard_version.noticeFrom "$2" > /dev/null 2>&1
        usi set eurogard_version.noticeTo "$3" > /dev/null 2>&1
        usi set eurogard_version.noticeMode "$4" > /dev/null 2>&1
        usi set eurogard_version.noticeReason "$5" > /dev/null 2>&1
    fi
    echo "state=$1 from=$2 to=$3 mode=$4 reason=$5"
}

busy() {
    for u in eurogard-ota-update eurogard-offline-update eurogard-rosp-update eurogard-nodered-activate; do
        systemctl is-active --quiet "${u}.service" 2> /dev/null && return 0
    done
    update_pending && return 0
    fuser /var/lib/dpkg/lock /var/lib/dpkg/lock-frontend > /dev/null 2>&1 && return 0
    return 1
}

# the router was reset to the factory state after the update started: the record is about a system that is gone
factory_reset_since() {
    [ -r "${RESTORE_CMD}" ] || return 1
    line=$(cat "${RESTORE_CMD}" 2> /dev/null)
    case "${line}" in
        *"factory restore at "*)
            ts=$(date -d "${line##*restore at }" +%s 2> /dev/null) || return 1
            [ "${ts}" -ge "$1" ] && return 0
            ;;
    esac
    return 1
}

cmd_start() {
    to=""
    mode="ota"
    while [ $# -gt 0 ]; do
        case "$1" in
            --to) to=$(printf '%s' "$2" | tr -cd 'A-Za-z0-9._+~:-'); shift 2 ;;
            --mode) mode=$(printf '%s' "$2" | tr -cd 'a-z'); shift 2 ;;
            *) shift ;;
        esac
    done
    [ -n "${to}" ] || { log "notice: start without a target version"; return 0; }
    from=$(core_version)
    # A retry of the SAME update (cut off by a power loss, the target version is installed or half installed already): the
    # version before the FIRST attempt is the one that counts. A record of an earlier update to the same version (the router
    # was reset since, /data survives) or an old one must not leak into a new update: the installed version is the start then.
    if [ -f "${NOTICE}" ] && [ "$(field TO)" = "${to}" ] && [ -n "$(field FROM)" ]; then
        old_started=$(field STARTED)
        if [ -n "${old_started}" ] && [ "$(( $(date +%s) - old_started ))" -lt "${RETRY_AGE}" ]; then
            if dpkg --compare-versions "${from:-0}" ge "${to}" || ! dpkg_clean; then
                from=$(field FROM)
            fi
        fi
    fi
    {
        echo "FROM=${from}"
        echo "TO=${to}"
        echo "MODE=${mode}"
        echo "STARTED=$(date +%s)"
        echo "BOOT=$(cat "${BOOT_ID_FILE}" 2> /dev/null)"
    } > "${NOTICE}.tmp" && mv -f "${NOTICE}.tmp" "${NOTICE}"
    sync
    log "notice: update ${from} -> ${to} (${mode}) recorded"
}

cmd_status() {
    if [ ! -f "${NOTICE}" ]; then
        publish none "" "" "" ""
        return 0
    fi
    from=$(field FROM)
    to=$(field TO)
    mode=$(field MODE)
    started=$(field STARTED)
    boot=$(field BOOT)
    now=$(date +%s)
    if [ -z "${to}" ] || [ -z "${started}" ] || [ "$((now - started))" -gt "${MAX_AGE}" ] || factory_reset_since "${started}"; then
        rm -f "${NOTICE}"
        log "notice: stale record dropped"
        publish none "" "" "" ""
        return 0
    fi
    if [ -n "${boot}" ] && [ "${boot}" = "$(cat "${BOOT_ID_FILE}" 2> /dev/null)" ]; then
        publish none "${from}" "${to}" "${mode}" ""
        return 0
    fi
    if busy; then
        publish running "${from}" "${to}" "${mode}" ""
        return 0
    fi
    installed=$(core_version)
    if dpkg_clean && [ -n "${installed}" ] && dpkg --compare-versions "${installed}" ge "${to}"; then
        publish success "${from}" "${to}" "${mode}" ""
    elif dpkg_clean; then
        publish incomplete "${from}" "${to}" "${mode}" version
    else
        publish incomplete "${from}" "${to}" "${mode}" dpkg
    fi
}

cmd_ack() {
    rm -f "${NOTICE}"
    sync
    log "notice: acknowledged"
    publish none "" "" "" ""
}

case "$1" in
    start) shift; cmd_start "$@" ;;
    status) cmd_status ;;
    ack) cmd_ack ;;
    *) echo "usage: notice start --to VERSION --mode ota|offline | status | ack" >&2 ;;
esac
exit 0
