#!/bin/sh
#
# Update from a USB stick. Called by eurogard_mount_backup_usb when the stick that was just mounted (/mnt/usb) has a
# folder "update". The folder holds ONE offline update bundle (eurogard-offline-update_<version>_arm64.deb, signed).
#
#   1. the bundle is checked (our package, not older than what is installed), copied to /upload/tempfile and handed to the
#      same steps as the upload on the version page: eurogard_offline_update_prepare, eurogard_offline_update_check
#      (signature of the Eurogard key), sysupgrade. The offline update unit then does the rest (restore point, packages,
#      firmware, message after the reboot), exactly like an update through the web page
#   2. LEDs: the USR LED flashes while the update is going on, "led marquee" when it is finished, the modem LED flashes
#      red when something went wrong. The previous state of the LEDs is restored when the stick is pulled after an error
#   3. a log is written to update/update.log on the stick (after an error and after a success)
#   4. after a successful update the router restarts as soon as the stick is pulled (the firmware needs the restart).
#      A bundle that is installed already ends with the marquee and no restart
#
# Switch: UCI eurogard_version.usb_update = false (Version > Settings) disables it, the stick is ignored then.
# Always exits 0: a failed unit would count for the failback check of the manufacturer, the LED and the log report errors.

USB=${EG_USB_ROOT:-/mnt/usb}
DIR=${USB}/update
UPLOAD=${EG_USB_UPLOAD:-/upload/tempfile}
LOGFILE=${EG_USB_LOG:-/tmp/eurogard-usb-update.log}
STATE_FILE=${EG_USB_STATE_FILE:-/run/eurogard_ota_update.state}
OFFLINE_DIR=${EG_USB_OFFLINE_DIR:-/app/eurogard/offline-update}
ROSP_DIR=${EG_USB_ROSP_DIR:-/app/eurogard/rosp-update}
LED_SAVE=${EG_USB_LED_SAVE:-/tmp/eurogard-usb-update.leds}
LED_SYS=${EG_USB_LED_SYS:-/sys/class/leds}
PREPARE=${EG_USB_PREPARE:-/usr/scripts/eurogard_offline_update_prepare}
CHECK=${EG_USB_CHECK:-/usr/scripts/eurogard_offline_update_check}
CANCEL=${EG_USB_CANCEL:-/usr/scripts/eurogard_offline_update_cancel}
SYSUPGRADE=${EG_USB_SYSUPGRADE:-sysupgrade}
WAIT_MAX=${EG_USB_WAIT_MAX:-4200}        # the whole update, seconds
START_MAX=${EG_USB_START_MAX:-180}       # sysupgrade has to get the update unit going within this time
POLL=${EG_USB_POLL:-3}

DEV=""
REBOOT=0

log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') $*" >> "${LOGFILE}"
    logger -t EurogardUsbUpdate "$*" 2> /dev/null
}

# --- LEDs ----------------------------------------------------------------------------------------------------------
led() { command led "$@" > /dev/null 2>&1; }

led_save() {
    : > "${LED_SAVE}"
    for l in modem rssi run status user; do
        d=${LED_SYS}/${l}
        [ -d "${d}" ] || continue
        trig=$(sed -n 's/.*\[\(.*\)\].*/\1/p' "${d}/trigger" 2> /dev/null)
        echo "${l} ${trig:-none} $(cat "${d}/delay_on" 2> /dev/null || echo -) $(cat "${d}/delay_off" 2> /dev/null || echo -) $(cat "${d}/brightness" 2> /dev/null || echo 0)" >> "${LED_SAVE}"
    done
}

led_restore() {
    killall ledd > /dev/null 2>&1
    [ -s "${LED_SAVE}" ] || return 0
    while read -r l trig on off bright; do
        d=${LED_SYS}/${l}
        [ -d "${d}" ] || continue
        echo "${trig}" > "${d}/trigger" 2> /dev/null
        [ "${on}" != "-" ] && echo "${on}" > "${d}/delay_on" 2> /dev/null
        [ "${off}" != "-" ] && echo "${off}" > "${d}/delay_off" 2> /dev/null
        [ "${trig}" = "none" ] && echo "${bright}" > "${d}/brightness" 2> /dev/null
    done < "${LED_SAVE}"
    led modem off
}

led_working() { led user flash; }
led_done() { led user off; ledd marquee > /dev/null 2>&1 & }
led_error() { killall ledd > /dev/null 2>&1; led modem red; led modem flash; }

# --- the stick -----------------------------------------------------------------------------------------------------
stick_present() {
    [ -d "${USB}" ] || return 1
    [ -z "${DEV}" ] || [ -b "${DEV}" ]
}

write_log_to_stick() {
    stick_present && [ -d "${DIR}" ] || return 0
    cp "${LOGFILE}" "${DIR}/update.log" 2> /dev/null
    sync
}

wait_for_removal() {
    log "Waiting for the stick to be pulled."
    while stick_present; do sleep 2; done
    log "The stick was pulled."
}

fail() {
    log "ERROR: $1"
    write_log_to_stick
    led_error
    wait_for_removal
    led_restore
    exit 0
}

# --- the update ----------------------------------------------------------------------------------------------------
installed_core() {
    dpkg-query -W -f='${db:Status-Abbrev} ${Version}' eurogardcore2 2> /dev/null
}

# the offline update (ours, also after a restart) is still busy
update_running() {
    systemctl is-active --quiet eurogard-offline-update.service 2> /dev/null && return 0
    [ -e "${OFFLINE_DIR}/pending" ] && return 0
    return 1
}

result_status() {
    sed -n 's/.*"status":"\([^"]*\)".*/\1/p' "${OFFLINE_DIR}/result.json" 2> /dev/null
}

# 0 = success, 1 = failed, 2 = timeout, 3 = the update did not start
wait_for_update() {
    waited=0
    while [ "${waited}" -lt "${WAIT_MAX}" ]; do
        st=$(cat "${STATE_FILE}" 2> /dev/null)
        # after a power loss /run is empty: the update resumed by itself, its persistent result tells the end
        if [ -z "${st}" ] && ! update_running; then
            st=$(result_status)
        fi
        case "${st}" in
            success) return 0 ;;
            failed) return 1 ;;
            uploading)
                [ "${waited}" -ge "${START_MAX}" ] && return 3
                ;;
        esac
        sleep "${POLL}"
        waited=$((waited + POLL))
    done
    return 2
}

add_details() {
    for f in "${OFFLINE_DIR}/offline-update.log" "${ROSP_DIR}/rosp-update.log"; do
        if [ -r "${f}" ]; then
            echo "--- last lines of ${f}" >> "${LOGFILE}"
            tail -n 25 "${f}" >> "${LOGFILE}" 2> /dev/null
        fi
    done
}

finish_ok() {
    if [ "${REBOOT}" = "1" ]; then
        log "The update is installed. The router restarts when the stick is pulled."
    else
        log "Nothing to install. Pull the stick."
    fi
    write_log_to_stick
    led_done
    wait_for_removal
    killall ledd > /dev/null 2>&1
    if [ "${REBOOT}" = "1" ]; then
        log "Restarting the router."
        sync
        reboot
    else
        led_restore
    fi
    exit 0
}

# ------------------------------------------------------------------------------------------------------------------
: > "${LOGFILE}"
[ -d "${DIR}" ] || exit 0

if [ "$(uci get eurogard_version.usb_update 2> /dev/null)" = "false" ]; then
    log "Update by USB stick is switched off (Version > Settings), the stick is ignored."
    exit 0
fi

MP=$(readlink -f "${USB}" 2> /dev/null)
DEV=$(awk -v m="${MP}" '$2 == m {print $1; exit}' /proc/mounts 2> /dev/null)
log "USB stick ${DEV:-?} found with an update folder (mounted at ${MP})."
led_save
led_working

# an online update is running: not now
if systemctl is-active --quiet eurogard-ota-update.service 2> /dev/null; then
    fail "Another update is running, try again when it is finished."
fi

# an update that was cut off (power loss with the stick still in) continues by itself: just wait for its end
if update_running; then
    log "An update is running already (it was resumed after a restart?), waiting for its end."
    REBOOT=1
    wait_for_update
    rc=$?
    add_details
    [ "${rc}" -eq 0 ] || fail "The update did not finish (code ${rc}), see the lines of the update log above."
    finish_ok
fi

BUNDLE=""
COUNT=0
for f in "${DIR}"/*.deb; do
    [ -f "${f}" ] || continue
    BUNDLE=${f}
    COUNT=$((COUNT + 1))
done
[ "${COUNT}" -ge 1 ] || fail "No update file found: put exactly one eurogard-offline-update_*.deb into the folder 'update' of the stick."
[ "${COUNT}" -eq 1 ] || fail "More than one .deb file in the folder 'update' (${COUNT}), the stick must hold exactly one update file."
log "Update file: $(basename "${BUNDLE}") ($(stat -c %s "${BUNDLE}" 2> /dev/null) bytes)"

PKG=$(dpkg-deb -f "${BUNDLE}" Package 2> /dev/null)
NEW=$(dpkg-deb -f "${BUNDLE}" Version 2> /dev/null)
[ "${PKG}" = "eurogard-offline-update" ] || fail "This is not an Eurogard update file (package '${PKG}')."
[ -n "${NEW}" ] || fail "The version of the update file cannot be read."

# the bundle carries the version of the eurogardcore2 it installs
CUR=$(installed_core)
CUR_STATUS=${CUR%% *}
CUR_VERSION=${CUR#* }
log "Update file version ${NEW}, installed eurogardcore2 ${CUR_VERSION:-none} (${CUR_STATUS:-none})."
if [ -n "${CUR_VERSION}" ] && [ "${CUR_STATUS}" = "ii" ]; then
    if dpkg --compare-versions "${NEW}" lt "${CUR_VERSION}"; then
        fail "The update file (${NEW}) is older than the installed version (${CUR_VERSION}). Downgrades are not done by USB stick."
    fi
    if [ "${NEW}" = "${CUR_VERSION}" ]; then
        log "Version ${NEW} is installed already, nothing to do."
        finish_ok
    fi
fi

# same steps as the upload on the version page
"${PREPARE}" || fail "Another update is running, try again when it is finished."
log "Copying the update file ..."
if ! cp "${BUNDLE}" "${UPLOAD}"; then
    rm -f "${UPLOAD}"
    fail "Copying the update file failed (not enough space?)."
fi
sync
if ! "${CHECK}"; then
    why=$(usi get eurogard_version.offlineCheck 2> /dev/null)
    rm -f "${UPLOAD}"
    "${CANCEL}"
    case "${why}" in
        signature) fail "The update file is not signed with the Eurogard key." ;;
        package) fail "This is not an Eurogard update file." ;;
        *) fail "The update file could not be verified (${why:-internal error})." ;;
    esac
fi
log "The signature is good, starting the installation."
if ! "${SYSUPGRADE}" "${UPLOAD}" >> "${LOGFILE}" 2>&1; then
    rm -f "${UPLOAD}"
    "${CANCEL}"
    fail "The installation could not be started."
fi

REBOOT=1
wait_for_update
rc=$?
add_details
case "${rc}" in
    0) finish_ok ;;
    1) fail "The update failed, see the lines of the update log above." ;;
    3) fail "The installation did not start." ;;
    *) fail "The update did not finish in time." ;;
esac
