#!/bin/sh
#
# Installs the newest eurogardcore2 through apt. When that version brings a firmware update
# (package eurogard-rosp-update, installed by its own systemd unit after apt has exited) this script
# keeps running until that update is finished, so "script finished" really means "update finished".
#
# Progress for the web UI:
#   - syslog tag EurogardUpdate (the log box on the version page)
#   - usi eurogard_version.installState  = running | system_update | success | failed
#     usi eurogard_version.installHeartbeat changes every few seconds while this script is alive
#
# Callers: eurogard_ota_update_start (web UI, detached) and the fleetdevice OtaUpdate action (synchronous).

# Log file path
LOG_FILE="/tmp/update_script.log"

# Journalctl identifier
JOURNAL_IDENTIFIER="EurogardUpdate"

# List of packages to install
PACKAGE_NAME="eurogardcore2"
# PACKAGES=("eurogardcore" "eurogard-web-files" "fleetdevice")
# PACKAGE_LIST=$(IFS=' '; echo "${PACKAGES[*]}")

LOCK_FILE="/run/eurogard_ota_update.lock"
STATE_FILE="/run/eurogard_ota_update.state"
CURSOR_FILE="/run/eurogard_ota_update.cursor"
ROSP_UPDATE_DIR="/app/eurogard/rosp-update"
ROSP_RESULT="${ROSP_UPDATE_DIR}/result.json"
ROSP_UNIT="eurogard-rosp-update.service"
SYSTEM_UPDATE_TIMEOUT=2400
HEARTBEAT_INTERVAL=5

VERSION_TO_INSTALL=$(usi get eurogard_version.core_latest)

# Function to log to journalctl and log file
log_message() {
    message="$1"
    logger -t "$JOURNAL_IDENTIFIER" "$message"
    echo "$message" >> "$LOG_FILE"
}

# Only one update at a time (web UI and fleet client could both start one)
exec 9> "$LOCK_FILE"
if ! flock -n 9; then
    log_message "Another update is already running."
    exit 1
fi

HEARTBEAT_PID=""
FINISHED=0

set_state() {
    echo "$1" > "$STATE_FILE"
    usi set eurogard_version.installState "$1" > /dev/null 2>&1
}

# The state is re-asserted every few seconds: the usi values live in memory and would be lost if the
# router service restarts during the update. The changing counter tells the web UI that we are alive.
start_heartbeat() {
    (
        n=0
        while true; do
            n=$((n + 1))
            usi set eurogard_version.installState "$(cat "$STATE_FILE" 2>/dev/null)" > /dev/null 2>&1
            usi set eurogard_version.installHeartbeat "$n" > /dev/null 2>&1
            sleep "$HEARTBEAT_INTERVAL"
        done
    ) 9>&- &
    HEARTBEAT_PID=$!
}

stop_heartbeat() {
    if [ -n "$HEARTBEAT_PID" ]; then
        kill "$HEARTBEAT_PID" 2>/dev/null
        wait "$HEARTBEAT_PID" 2>/dev/null
        HEARTBEAT_PID=""
        sleep 1
    fi
}

# finish success|failed
finish() {
    FINISHED=1
    echo "$1" > "$STATE_FILE"
    stop_heartbeat
    set_state "$1"
}

# Executed on every exit: if we get killed or exit without finishing, the web UI must not wait forever
cleanup() {
    if [ "$FINISHED" -eq 0 ]; then
        log_message "Error: update aborted unexpectedly."
        finish failed
    fi
    rm -f "$CURSOR_FILE"
}
trap cleanup EXIT
trap 'exit 1' INT TERM HUP

fail() {
    log_message "$1"
    if [ -d "/mnt/usb/" ]; then
        cp "$LOG_FILE" "/mnt/usb/update_script_error.log"
    fi
    finish failed
    exit 1
}

set_state running
start_heartbeat

# The target version is written by eurogard_check_ota_update_versions
case "$VERSION_TO_INSTALL" in
    ""|*" "*)
        fail "Error: No update version known. Please check for updates first."
        ;;
esac

# Check for internet connectivity
ping -c 1 -4 eurogard.de > /dev/null 2>&1
if [ $? -ne 0 ]; then
    fail "Error: No internet connection."
fi

# Update apt sources
log_message "Updating apt sources..."
apt update 2>&1 | while IFS= read -r line; do log_message "$line"; done

# apt only considers the newest version of a dependency. An exact pin of the target version, e.g.
# "Pre-Depends: eurogard-web-files2 (= 1.3.3)", can therefore not be met when the repository holds a newer
# web-files2 ("... but 1.4.0 is to be installed"). So every exactly pinned dependency of the target version is
# named on the command line as well.
pinned_dependencies() {
    apt-cache show "${PACKAGE_NAME}=${VERSION_TO_INSTALL}" 2>/dev/null |
        sed -n 's/^\(Pre-Depends\|Depends\): //p' |
        tr ',' '\n' |
        grep -v '|' |
        sed -n 's/^ *\([a-z0-9][a-z0-9+.-]*\) *(= *\([^)]*\)) *$/\1=\2/p' |
        sort -u
}
PINNED_DEPENDENCIES=$(pinned_dependencies | tr '\n' ' ')

# The user is told after the reboot whether this update completed (web UI, failsafe/notice)
if [ -x /usr/lib/eurogard/failsafe/notice ]; then
    /usr/lib/eurogard/failsafe/notice start --to "${VERSION_TO_INSTALL}" --mode ota > /dev/null 2>&1
fi

# Restore point for the failback of RobustOS 2.4.x (best effort, never stops the update)
if [ -x /usr/lib/eurogard/failsafe/backup ]; then
    log_message "Creating the restore point."
    /usr/lib/eurogard/failsafe/backup --target "${PACKAGE_NAME}=${VERSION_TO_INSTALL}" 2>&1 | while IFS= read -r line; do log_message "$line"; done
fi

# A power loss during an earlier installation can leave one of the packages half installed ("iHR", "iUR", ...). apt then
# refuses everything ("Unmet dependencies ... not going to be installed"), even online, because the half installed version
# still pins its dependencies. The target versions come from the repository, so the broken ones are removed first
# (only the packages of this update, never vendor packages; the configuration is kept, dpkg --remove does not purge).
for pkg in ${PACKAGE_NAME} eurogard-web-files2 eurogard-web-files3 eurogard-nodered eurogard-rosp-update; do
    st=$(dpkg-query -W -f='${db:Status-Abbrev}' "$pkg" 2>/dev/null | tr -d ' ')
    case "$st" in
        ?H*|?U*|?F*|?W*|?t*|??R)
            log_message "Package $pkg was left half installed ($st), removing it before the installation."
            dpkg --remove --force-remove-reinstreq --force-depends "$pkg" < /dev/null 2>&1 | while IFS= read -r line; do log_message "$line"; done
            ;;
    esac
done

# Install required packages. The exit status of apt is passed through a file, $? after a pipe is the
# status of the last command in the pipe (the log loop), not of apt.
log_message "Installing: $PACKAGE_NAME=$VERSION_TO_INSTALL $PINNED_DEPENDENCIES"
APT_RC_FILE=$(mktemp)
{ apt install -y $PACKAGE_NAME=$VERSION_TO_INSTALL $PINNED_DEPENDENCIES 2>&1 9>&-; echo $? > "$APT_RC_FILE"; } |
    while IFS= read -r line; do log_message "$line"; done
APT_RC=$(cat "$APT_RC_FILE" 2>/dev/null)
rm -f "$APT_RC_FILE"

if [ "$APT_RC" != "0" ]; then
    fail "Error: Installation failed."
fi

# --- firmware update -------------------------------------------------------------------------------
# The new eurogardcore2 may depend on eurogard-rosp-update. Its postinst only schedules the firmware
# update (it cannot run inside apt's dpkg lock), a systemd unit does the work once apt has exited.

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

# Copies new log lines of the firmware installer to the update log (journal cursor: no duplicates)
forward_system_log() {
    journalctl -t rosp-backend -t eurogard-rosp-update -o cat --no-pager --cursor-file="$CURSOR_FILE" 2>/dev/null |
        while IFS= read -r line; do log_message "System update: $line"; done
}

wait_for_system_update() {
    set_state system_update
    log_message "The device software is being updated now. This takes a few minutes, do not power off the device."

    # start at the current end of the journal, older entries belong to earlier runs
    rm -f "$CURSOR_FILE"
    journalctl -t rosp-backend -t eurogard-rosp-update -n 1 -o cat --no-pager --cursor-file="$CURSOR_FILE" > /dev/null 2>&1

    waited=0
    unit_idle=0
    while [ "$waited" -lt "$SYSTEM_UPDATE_TIMEOUT" ]; do
        forward_system_log
        status=$(result_status)
        case "$status" in
            success|current)
                forward_system_log
                log_message "System update installed. A restart is required."
                return 0
                ;;
            failed|gave_up|lock_timeout)
                forward_system_log
                log_message "Error: System update failed (${status}). Details: ${ROSP_UPDATE_DIR}/rosp-update.log"
                return 1
                ;;
        esac

        if [ ! -e "${ROSP_UPDATE_DIR}/pending" ] && [ -z "$status" ]; then
            # marker removed without a result, nothing left to wait for
            return 0
        fi

        # the unit has to take over within a minute, otherwise nothing will ever happen
        if [ "$status" = "scheduled" ] || [ -z "$status" ]; then
            if systemctl is-active --quiet "$ROSP_UNIT"; then
                unit_idle=0
            else
                unit_idle=$((unit_idle + 1))
            fi
            if [ "$unit_idle" -ge 20 ]; then
                log_message "Error: The system update service did not start."
                return 1
            fi
        else
            unit_idle=0
        fi

        sleep 3
        waited=$((waited + 3))
    done

    log_message "Error: The system update did not finish in time."
    return 1
}

if [ -e "${ROSP_UPDATE_DIR}/pending" ]; then
    if ! wait_for_system_update; then
        fail "Error: Update failed."
    fi
fi

log_message "Update finished."
finish success
exit 0
