#!/bin/sh
#
# Web UI entry point for the update. Runs eurogard_ota_update as its own systemd unit and returns at once.
#
# Why: the web server has a single worker and a script started through custom_btn_callback blocks every
# other request, including the polling of the log and of the update state, until it exits. Started
# detached, the page stays responsive and shows live progress.

UNIT="eurogard-ota-update"

# Already running (started by the web UI or the fleet client): the page just attaches to it.
if systemctl is-active --quiet "${UNIT}.service"; then
    exit 0
fi

# The page polls this value as soon as we return, set it first or it could still read an old "success".
usi set eurogard_version.installState running > /dev/null 2>&1

systemctl reset-failed "${UNIT}.service" > /dev/null 2>&1
if ! systemd-run --no-block --collect --unit="${UNIT}" /usr/scripts/eurogard_ota_update > /dev/null 2>&1; then
    usi set eurogard_version.installState failed > /dev/null 2>&1
    exit 1
fi

exit 0
