#!/bin/sh
# Update the installed systems from a published release, on the device itself.
#   mu300-update check            what is installed, what is the newest release
#   mu300-update version          what is installed (no network needed)
#   mu300-update apply [OS...]    download, unpack and switch (default: every installed system), then the kernel and
#                                 the boot image (MU300_UBUNTU=24.04|26.04: move Ubuntu to that release). Everything
#                                 you added to the system or changed in it is carried over; packages installed on the
#                                 device are installed again at the first boot (--no-reinstall: not). --no-rollback:
#                                 the previous system is not kept, which needs no room for a copy of your files
#   mu300-update report           what the last updates carried over, set aside or put back (/etc/mu300/update-report)
#   mu300-update boot             only the kernel and the boot image
#   mu300-update rollback [OS]    go back to the previous version kept as <os>.old
#   mu300-update rollback-boot    go back to the previous boot image
#   mu300-update kernel [5.4|6.18|7.3]  show, or change, the kernel (vendor 5.4, mainline 6.18 LTS or 7.3 stable) and
#                                 install it (7.2 is retired: a device that chose it gets 7.3 with its next update)
#   mu300-update clean            delete the kept <os>.old copies
#   mu300-update notice           only look: a note for the login message and mu300-toolkit when a newer release is
#                                 out (at boot and every 6 hours; nothing is installed without apply)
#   mu300-update source [URL|off]  show where the release files come from (the environment, /etc/mu300/update-source,
#                                 or GitHub), put a mirror of them in that file (URL), or take it out (off). A mirror
#                                 that cannot be reached is said once, and the rest of that run comes from GitHub
#   mu300-update apply --from FILE|DIR   the same update without the network: from a Magisk zip of a release, or a
#                                 directory with a release's files and their SHA256SUMS (--unsigned: one the project's
#                                 release key cannot vouch for)
#   mu300-update apply --downgrade   go to a release older than what is installed (online or --from): never by itself
#   mu300-update status|releases|inspect FILE   JSON for a panel (see "for a panel" below)
# Installed extras (mu300-extra: LuCI's languages) are updated with the release, the VPN module (mu300-vpn and its
# engines, from github.com/dikeckaan/mu300-linux-vpn) to its latest release. A device that uses the VPN is never left
# without it or its engines: when they cannot be had, apply stops before it changes anything (MU300_VPN_MODULE=FILE|DIR,
# or the module's tarballs and SHA256SUMS copied to /mnt/mu300-disk/.mu300-update/vpn/, serve them offline).
#
# How it works: the new filesystem is unpacked next to the old one as <os>.new on the Linux partition, everything
# that is yours in the old one (what its image did not bring, or brought and you changed: the carry block) and the
# vendor files are carried over, and only then are the directories swapped (<os> -> <os>.old, <os>.new -> <os>).
# Renaming the directory a running system boots from is safe - the running processes keep the old one until the
# next boot - so an interrupted download or unpack can never leave a half-updated system behind.
#
# The kernel and the boot image are updated here too, from releases that carry the generic boot ramdisk segment (see
# boot_update). An mu300-update from before that installs the new system, which brings the new mu300-update: after
# a reboot (the running system is still the old one until then), "mu300-update apply" updates the boot image too.
export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/sbin:/sbin"
REPO=${MU300_REPO:-dikeckaan/mu300-linux}
DISK=${MU300_DISK:-/mnt/mu300-disk}
CONF=/etc/mu300
VERSION_FILE=$CONF/image-version
SYSTEMS="ubuntu openwrt openwrt-luci"
# what this process's environment said about the release source, before source_conf fills the variables in from
# /etc/mu300/update-source: the environment wins, so `mu300-update source` has to be able to say which of the two
# is in force, and the file's value is indistinguishable from an environment one once it is in the variable
SOURCE_ENV_DL=${MU300_DOWNLOAD_URL:-}
SOURCE_ENV_API=${MU300_API_URL:-}
# a system's kind decides which files are its settings and how its accounts look (spec D2)
os_kind() { case $1 in ubuntu) echo ubuntu ;; openwrt|openwrt-*) echo openwrt ;; *) return 1 ;; esac; }

say() { printf '\n==> %s\n' "$*"; }
# (the private copies of the VPN module's tarballs go with it: MODULE_VDIR, module_vdir)
die() { [ -z "${MODULE_VDIR:-}" ] || rm -rf "$MODULE_VDIR"; printf '\nERROR: %s\n' "$*" >&2; exit 1; }
have() { command -v "$1" >/dev/null 2>&1; }

# Why a download could not connect, for the line that says it failed. The VPN's kill switch (mu300-vpn, nft table
# inet mu300_vpn) lets nothing of this device out on an uplink while its tunnel is down: the device's own downloads
# are no exception, and that is the promise (FINDINGS 170). uclient-fetch, OpenWrt's wget, then prints "Failed to send
# request: Operation not permitted" - its connect error code (1) passed to strerror, which it prints for every
# connection that could not be made - and "is the device online?" sent people looking for a dead modem.
# vpn_ks_blocks: the kill switch is up and this device's own traffic is not routed into a tunnel (it would leave on
# the cellular interface or the Wi-Fi client, or there is no route at all). (MU300_KS_ROUTE: tests/, ip route get's
# answer in its place; MU300_WIFI_IFACE as for mu300-vpn)
vpn_ks_blocks() {
    have nft || return 1
    _kt=$(nft list table inet mu300_vpn 2>/dev/null) || return 1
    # (mu300-vpn's download window, its own engine download: the release hosts are let out, so not this)
    case $_kt in *"set fetch4"*) return 1 ;; esac
    if [ -n "${MU300_KS_ROUTE+x}" ]; then _kr=$MU300_KS_ROUTE; else _kr=$(ip -4 route get 1.1.1.1 2>/dev/null) || _kr=; fi
    case " $_kr " in
        *" dev sipa_eth"*|*" dev ${MU300_WIFI_IFACE:-wlan0} "*|"  ") return 0 ;;
    esac
    return 1
}
# offline_why: the reason, in the words of the line it ends
offline_why() {
    if vpn_ks_blocks; then
        echo "blocked by the VPN kill switch: the VPN is on and its tunnel is not up, and nothing leaves this device" \
            "outside it - see mu300-vpn status, and try again once the tunnel is up"
    else
        echo "is the device online?"
    fi
}

# A transfer that stalls is cut off and retried rather than waited for: with older boot images the IPA's downlink
# can die in the middle of one (docs/FINDINGS.md 32), and without a timeout the update hung for good.
# A network error is tried again a few times (MU300_FETCH_DELAY s apart): right after boot the VPN comes up some
# seconds after mobile data, and a request in between is reset - "check" then said GitHub could not be reached.
# curl's own --retry leaves resets alone. Only a failed connection is retried here (curl 6 7 35 52 56; wget 4, GNU's
# network failure - busybox wget says 1 for everything and is not): an HTTP error (22, a 404) is an answer, and a
# timeout (28) has been retried by curl already (four more rounds would hold "check" for half an hour).
# The release source of this run, and what to do when a mirror cannot be reached. A mirror may be down - a
# third-party proxy is allowed to be - so a run that cannot reach it says so once and takes the rest of that run
# from github.com. What counts as "cannot reach it" is the careful part: a failure is not the source's absence when
# it delivered bytes before it failed. A large file from a working mirror stalls on a bad line, and curl cuts it at
# --speed-time with 28 (or 52/56 once the transfer started) - moving that run to github.com would take the update
# where the person who set a mirror often cannot go. So 28 and 56 count only when the caller says nothing arrived
# (fetch_file measures the file); 6 7 35 52 are the codes that cannot have delivered anything: no name, no
# connection, no TLS, an empty reply. An HTTP error, a wrong hash or a bad signature is the source's answer too,
# never its absence, and stops the run as it always did. The fetchers report that failure as exit 9 so the caller
# can act on it in its own process: a subshell's assignments do not survive, and $(fetch_stdout ...) is one.
# Nothing is written down - the next run tries the mirror again - but a self-update handover does pass the state on
# (mirror_fell_back), so the updater of the new release does not wait for the same mirror all over again.
FETCH_UNREACHABLE=9
SOURCE_FELL_BACK=
# The "said once" lines of mirror_fell_back go to the run's own stderr, kept here as fd 7: apply's first fetch (its
# self-update check, "fetch_verified TAG mu300-update 2>/dev/null") is where a mirror is usually found unreachable,
# and the line said there went to /dev/null - the run then fell back, or stopped, without a word (F50-B, 2026-10-17)
exec 7>&2
# MU300_MIRROR_FALLBACK in /etc/mu300/update-source (the file is the only place that says so, never the
# environment - source_conf): 0 never moves a run to github.com, 1 always may, and without the line (auto) only an
# https mirror on a public name does. A plain-http mirror or one on a private address is almost always a copy on the
# LAN, set up so the release does not come over the mobile link; when that box is off, a silent move to github.com
# would take the whole release over a metered SIM. So there the run stops and says why, as it did before there was
# a mirror, and the line in the file is how to allow it.
MIRROR_FALLBACK=auto
# fetch_unreachable_rc RC [ARRIVED]: 9 when RC is a mirror of this run that could not be reached, 1 for every other
# failure (which is what these two fetchers have always returned). ARRIVED is 0 when the caller knows nothing came
# back, 1 when it knows bytes did, unset when it cannot tell. Whether the run may then move to github.com is
# mirror_fell_back's decision, in the caller's own process
fetch_unreachable_rc() {
    [ "${2:-}" != 1 ] || { printf '1\n'; return; }
    case $1 in
        6|7|35|52) ;;                                          # never answered
        28|56) [ "${2:-}" = 0 ] || { printf '1\n'; return; } ;;  # cut off, or answered: only nothing counts
        *) printf '1\n'; return ;;
    esac
    [ -n "${MU300_RELEASE_URL:-}${MU300_DOWNLOAD_URL:-}" ] || { printf '1\n'; return; }
    [ -z "$SOURCE_FELL_BACK" ] || { printf '1\n'; return; }
    printf '%s\n' "$FETCH_UNREACHABLE"
}
# mirror_local URL: true when URL is plain http, or its host is a private, loopback or link-local address or a name
# only a LAN resolves (no dot; .lan .local .home .home.arpa .internal .localdomain .localhost)
mirror_local() {
    case $1 in https://*) ;; *) return 0 ;; esac
    _mh=${1#https://}; _mh=${_mh%%/*}; _mh=${_mh%:*}
    _mh=$(printf '%s' "$_mh" | tr 'A-Z' 'a-z')
    case $_mh in
        *.*) ;;
        *) return 0 ;;
    esac
    case $_mh in
        localhost|*.localhost|*.lan|*.local|*.home|*.home.arpa|*.internal|*.localdomain) return 0 ;;
        10.*|127.*|192.168.*|169.254.*) return 0 ;;
        172.1[6-9].*|172.2[0-9].*|172.3[01].*) return 0 ;;
    esac
    return 1
}
# say_run FORMAT ARGS: printf to the run's stderr (fd 7), whatever the caller did with its own; stderr without fd 7
say_run() { { printf "$@" >&7; } 2>/dev/null || printf "$@" >&2; }
# mirror_fell_back: in the caller's own process - say it once, and use github.com for the rest of this run; or,
# where the fallback is not allowed (MIRROR_FALLBACK), say once why the run stays with the mirror, and fail
mirror_fell_back() {
    [ -z "$SOURCE_FELL_BACK" ] || return 1
    _mwhy=
    case $MIRROR_FALLBACK in
        0) _mwhy="MU300_MIRROR_FALLBACK=0 in $SOURCE_CONF" ;;
        1) ;;
        *) ! mirror_local "${MU300_RELEASE_URL:-${MU300_DOWNLOAD_URL:-}}" ||
               _mwhy="a plain-http or LAN mirror; MU300_MIRROR_FALLBACK=1 in $SOURCE_CONF allows it" ;;
    esac
    if [ -n "$_mwhy" ]; then
        [ -n "${MIRROR_STAYED:-}" ] ||
            say_run 'mirror unreachable: the release is not taken from github.com instead (%s)\n' "$_mwhy"
        MIRROR_STAYED=1
        return 1
    fi
    SOURCE_FELL_BACK=1
    # apply hands over to the release's own updater in this very environment ("exec sh $STAGE/mu300-update"): it
    # would read the source file again and wait for the same mirror, so the state goes along with it
    export MU300_MIRROR_FELL_BACK=1
    # both sides: the line says the rest of this run comes from github.com, and it has to be true of the release
    # listing too (a device that named an API mirror would otherwise still ask it)
    MU300_RELEASE_URL= MU300_DOWNLOAD_URL= MU300_API_URL=
    SUMS_FETCHED= SUMS_OK= SUMS_PIN=
    say_run 'mirror unreachable: the rest comes from github.com\n'
    return 0
}
# fetch_base TAG: the directory this run takes release TAG's files from (MU300_RELEASE_URL is the whole base, the
# tag included, as it always was; MU300_DOWNLOAD_URL is the one the tag is added to)
fetch_base() {
    [ -z "$SOURCE_FELL_BACK" ] || { printf '%s\n' "https://github.com/$REPO/releases/download/$1"; return; }
    printf '%s\n' "${MU300_RELEASE_URL:-${MU300_DOWNLOAD_URL:-https://github.com/$REPO/releases/download}/$1}"
}
fetch_stdout() {  # fetch_stdout URL (exit 9: the mirror of this run could not be reached)
    _try=1
    while :; do
        if have curl; then _out=$(curl -fsSL --connect-timeout 30 --max-time 120 --retry 3 "$1"); _rc=$?
            case $_rc in 0|6|7|35|52|56) ;; *) return "$(fetch_unreachable_rc "$_rc")" ;; esac
        else _out=$(wget -T 60 -qO- "$1"); _rc=$?
            case $_rc in 0|4) ;; *) return "$(fetch_unreachable_rc "$_rc")" ;; esac
        fi
        [ "$_rc" = 0 ] && { printf '%s\n' "$_out"; return 0; }
        [ "$_try" -ge 4 ] && return "$(fetch_unreachable_rc "$_rc")"
        # behind the kill switch with the tunnel down, three more rounds are three more minutes of the same
        ! vpn_ks_blocks || return 1
        _try=$((_try + 1))
        sleep "${MU300_FETCH_DELAY:-4}"
    done
}
fetch_file() {  # fetch_file URL OUT (resumes a partial OUT; exit 9: the mirror of this run could not be reached)
    # what the file holds before the attempt: a transfer that arrived and then failed wrote bytes, and that is a
    # source that answered - the loop resumes it here rather than moving the run to github.com
    _had=$(wc -c 2>/dev/null < "$2" || printf '0\n')
    if have curl; then
        curl -fL --retry 5 --retry-delay 5 --connect-timeout 30 --speed-limit 1024 --speed-time 60 -C - -o "$2" "$1"
        _rc=$?
    else wget -c -T 60 -O "$2" "$1"; _rc=$?; fi
    [ "$_rc" = 0 ] && return 0
    _now=$(wc -c 2>/dev/null < "$2" || printf '0\n')
    if [ "$_now" -gt "$_had" ]; then return 1; fi
    return "$(fetch_unreachable_rc "$_rc" 0)"
}

# fetch_verified TAG ASSET: the release file in $STAGE, checked against the release's SHA256SUMS; a file that is
# already there and matches is not downloaded again, a partial one is resumed. 2: the release has no such file;
# 3: the release itself was refused (its signature, or its checksums are another release's) - trying again changes
# nothing, so apply does not say it would (fetch_stop)
STAGE=$DISK/.mu300-update
fetch_verified() {
    progress file "$2"
    # (apply --from: the release is a file or a directory, see from_verified)
    [ -z "${MU300_FROM:-}" ] || { from_verified "$@"; return; }
    # the release source of this run (MU300_RELEASE_URL: another server with the same files and SHA256SUMS, as for
    # install.sh - fetch_base knows the three of them)
    base=$(fetch_base "$1")
    stage_private || return 1
    # SHA256SUMS is fetched once per run, never trusted from an earlier one: a release published again under the
    # same tag left a stale copy that every file then failed (and the updater it had verified replaced this one).
    # Only without GitHub does the kept copy of the same tag stand in.
    if [ "${SUMS_FETCHED:-}" != "$1" ]; then
        _sums=$(fetch_stdout "$base/SHA256SUMS"); _src=$?
        # a mirror this run cannot reach: once, and github.com for everything left (its checksums too)
        if [ "$_src" = "$FETCH_UNREACHABLE" ] && mirror_fell_back; then
            base=$(fetch_base "$1"); _sums=$(fetch_stdout "$base/SHA256SUMS"); _src=$?
        fi
        if [ "$_src" = 0 ] && [ -n "$_sums" ]; then
            printf '%s\n' "$_sums" > "$STAGE/SHA256SUMS"
            echo "$1" > "$STAGE/SHA256SUMS.tag"
            SUMS_FETCHED=$1
        elif [ "$(cat "$STAGE/SHA256SUMS.tag" 2>/dev/null)" != "$1" ] || [ ! -s "$STAGE/SHA256SUMS" ]; then
            echo "cannot download SHA256SUMS of $1" >&2
            return 1
        fi
    fi
    # (where this system has the project's release key: the signature of SHA256SUMS, see sums_trusted)
    sums_trusted "$1" "$base" || return 3
    want=$(awk -v f="$2" '$2 == f || $2 == "*" f {print $1}' "$STAGE/SHA256SUMS")
    [ -n "$want" ] || { echo "$2 is not part of release $1" >&2; return 2; }
    for try in 1 2 3; do
        [ -s "$STAGE/$2" ] && [ "$(sha256sum "$STAGE/$2" | cut -d' ' -f1)" = "$want" ] && return 0
        fetch_file "$base/$2" "$STAGE/$2"; _frc=$?
        [ "$_frc" = 0 ] && [ "$(sha256sum "$STAGE/$2" | cut -d' ' -f1)" = "$want" ] && return 0
        # the same as for the checksums: the mirror is gone, so this file and the checksums come from github.com
        if [ "$_frc" = "$FETCH_UNREACHABLE" ] && mirror_fell_back; then base=$(fetch_base "$1"); fi
        # a corrupt or stale file cannot be resumed: start over. The kept SHA256SUMS may be the stale part - a
        # release published again under the same tag - so it is fetched again too.
        rm -f "$STAGE/$2"
        if _sums=$(fetch_stdout "$base/SHA256SUMS") && [ -n "$_sums" ]; then
            printf '%s\n' "$_sums" > "$STAGE/SHA256SUMS"
            SUMS_FETCHED=$1; SUMS_OK=; sums_trusted "$1" "$base" || return 3
            want=$(awk -v f="$2" '$2 == f || $2 == "*" f {print $1}' "$STAGE/SHA256SUMS")
            [ -n "$want" ] || { echo "$2 is not part of release $1" >&2; return 2; }
        fi
        sleep 5
    done
    echo "downloading $2 failed" >&2
    return 1
}

# The release file of a system. Ubuntu comes as 24.04 (mu300-ubuntu-rootfs.tar.gz) and as 26.04: an update keeps the
# release that is installed (its os-release says which); MU300_UBUNTU=24.04|26.04 moves to the other one.
rootfs_asset() {  # rootfs_asset OS
    [ "$1" = ubuntu ] || { echo "mu300-$1-rootfs.tar.gz"; return; }
    u=${MU300_UBUNTU:-$(sed -n 's/^VERSION_ID="\(.*\)"/\1/p' "$DISK/ubuntu/etc/os-release" 2>/dev/null)}
    case $u in 26.04) echo mu300-ubuntu-26.04-rootfs.tar.gz ;; *) echo mu300-ubuntu-rootfs.tar.gz ;; esac
}

# Unpack with GNU tar, and with busybox tar when that fails: the GNU tar of Ubuntu 26.04 needs openat2(), which
# kernel 5.4 does not have ("Cannot open: Function not implemented" for everything below the top directory), and
# busybox tar is on both systems. Without this a 26.04 that ended up on 5.4 could not even install another kernel.
untar() {
    tar "$@" 2>/dev/null && return 0
    command -v busybox >/dev/null && busybox tar "$@"
}

installed_version() { [ -r "$VERSION_FILE" ] && cat "$VERSION_FILE" || echo unknown; }
this_device() { "${MU300_BIN:-/opt/mu300/bin}/mu300-device"; }
# A new boot image must never meet a locked slot (mu300-next-boot lock): its first boots are the usual attempts, and
# the first one that gets to mu300-boot-ok locks again. Two states leave it without them, and saying nothing about
# either is how an update on such a device ended with the operator rebooting into Android while the screen said
# "Reboot to start the updated openwrt-luci" (2026-10-12, a U30 Air): the default boot is Android, so the image is
# not tried at all and a reboot goes there (exit 3), or this slot's block cannot be rebuilt, so the image gets one
# boot instead of N (any other failure, and mu300-next-boot's own line is passed on). Quiet when it was armed.
# Never fails the update: the boot image is written either way, and a warning is no reason to roll it back.
# The running system's mu300-next-boot first. One from before --trial (an older release, or another installer's
# system: issue #290) answers with its usage line and exit 2; then the copy in the system this update has just
# installed does it - the running system's first, then the others - as the new boot image's own tool.
unlock_for_trial() {
    _found= _rc=0 _out=
    for _nb in "${MU300_BIN:-/opt/mu300/bin}/mu300-next-boot" "$DISK/$(running_os)/opt/mu300/bin/mu300-next-boot" \
               $(for _o in $(installed_systems); do printf '%s ' "$DISK/$_o/opt/mu300/bin/mu300-next-boot"; done); do
        [ -x "$_nb" ] || continue
        _found=1 _rc=0
        _out=$("$_nb" --trial 2>&1) || _rc=$?
        if [ "$_rc" = 2 ]; then case $_out in *usage:*) continue ;; esac; fi
        break
    done
    [ -n "$_found" ] || return 0
    case $_rc in
        0) ;;
        3) echo "boot: the default boot is Android, so this boot image gets no trial: only a boot from Android" >&2
           echo "      tries it (mu300-linux, or the panel)" >&2 ;;
        *) echo "boot: could not arm the Linux slot for a trial (mu300-next-boot --trial)${_out:+: $_out}" >&2 ;;
    esac
}

# Where the next boot goes: mu300-next-boot's file (MU300_DEFAULT_BOOT, /etc/mu300/default-boot - the knob is for
# tests). With Android as the default boot every Linux boot is a one-shot trial armed from Android (mu300-linux, the
# panel's switch), so a plain reboot does not start what was just written or switched. Says what to do instead and
# returns true then; false when Linux is the default, and the caller's own "Reboot to start it" is what happens.
reboot_goes_to_android() {
    [ "$(cat "${MU300_DEFAULT_BOOT:-/etc/mu300/default-boot}" 2>/dev/null)" = linux ] && return 1
    echo 'The default boot is Android, so a reboot goes to Android by itself. Start Linux by hand (mu300-linux, or'
    echo '"Switch to Linux" on the panel), and keep it: mu300-next-boot linux'
    return 0
}

# bundle_runs_here BUNDLE LIST DIR: does this kernel bundle (LIST: its file list) run on this device? Bundles name
# their devices in ./devices; one without it is from before the U30 Air and runs on the F50 only (see boot_update).
bundle_runs_here() {
    _me=$(this_device)
    [ "$_me" = f50 ] && return 0
    grep -qx './devices' "$2" || return 1
    untar -xzf "$1" -C "$3" ./devices && grep -qw "$_me" "$3/devices"
}
# A system on the SD card boots only with a kernel that has the SD host (the bundle says so in ./features). Installing
# an older bundle there would leave a device that cannot find its own root filesystem. Where the system is comes from
# root_layout: /run/mu300-root-dev, the internal region being "<eMMC>@<offset>" (the eMMC is not always mmcblk0,
# 31l), or for another installer's init the card that /run/mu300/disk-dev names.
root_on_sd() { [ "$(root_layout)" = sd ]; }
# bundle_has BUNDLE LIST FEATURE: does the bundle (LIST: its file list) list FEATURE in ./features?
bundle_has() { grep -qx './features' "$2" && untar -xzOf "$1" ./features 2>/dev/null | grep -qx "$3"; }
# root_layout: where the running system's disk is, as the init of a boot image has to find it. region: the area
# after the eMMC's last partition; sd: the card; part: a GPT partition named mu300root; image: a file inside a
# filesystem (Android's userdata); unknown. This project's init writes where in /run/mu300-root-dev. The init of
# another installer - kanoqwq's desktop installer, whose "independent partition" and "userdata image" are part and
# image - leaves only /run/mu300/disk-dev, the device it mounted (issue #290); a device of a disk the kernel calls
# an SD card is his TF installation (from kanoqwq's 5161859d).
root_layout() {
    _rd=$(cat "${MU300_ROOT_DEV_FILE:-/run/mu300-root-dev}" 2>/dev/null)
    case $_rd in
        '') ;;
        *@mu300root) echo part; return ;;
        *@*) echo region; return ;;
        *) echo sd; return ;;
    esac
    _dd=$(cat "${MU300_SYSROOT:-}/run/mu300/disk-dev" 2>/dev/null); _dd=${_dd##*/}
    _sb=${MU300_SYSROOT:-}/sys/class/block/$_dd
    case $_dd in
        '') echo unknown ;;
        loop*) case $(cat "$_sb/loop/backing_file" 2>/dev/null) in
                   '') echo unknown ;;
                   /dev/*) echo region ;;
                   *) echo image ;;
               esac ;;
        *) if grep -qx 'PARTNAME=mu300root' "$_sb/uevent" 2>/dev/null; then echo part
           elif [ "$(cat "${MU300_SYSROOT:-}/sys/class/block/${_dd%p[0-9]*}/device/type" 2>/dev/null)" = SD ]; then echo sd
           else echo unknown; fi ;;
    esac
}
# bundle_finds_root BUNDLE LIST: can the init of this bundle find the running system's disk? Not in a file (no init
# of ours mounts Android's userdata), and in a GPT partition only when the bundle says so (gpt-root in ./features).
# Without this, such a device got the new boot image, found no system, waited 5 minutes in the rescue shell and went
# back to Android (issue #290: a V50 installed with kanoqwq's desktop installer).
bundle_finds_root() {
    case $(root_layout) in
        image) return 1 ;;
        part) bundle_has "$1" "$2" gpt-root ;;
        *) return 0 ;;
    esac
}
root_not_found_msg() {
    case $(root_layout) in
        image) _w='in an image file inside Android'"'"'s userdata' ;;
        *) _w='in the GPT partition mu300root' ;;
    esac
    printf 'this system runs from %s (an installation by another installer), and the init of this kernel bundle cannot find it there: the device would wait 5 minutes in the rescue shell and go back to Android (issue #290)' "$_w"
}
# bundle_has_sd BUNDLE LIST: does the bundle say it has the SD host?
bundle_has_sd() { bundle_has "$1" "$2" sdcard; }
# bundle_fits_slot BUNDLE LIST: can its init run from the slot Linux is on? One from before linux-slot knows only b:
# on a it would restore the block that boots Linux, marked successful, and log into Android's boot partition.
bundle_fits_slot() { [ "$(linux_slot)" = b ] || bundle_has "$1" "$2" linux-slot; }
# copy_missing FROM TO: copy what FROM has and TO lacks, never replacing anything of TO. Not `cp -an FROM/. TO/`:
# busybox cp -n skips a directory that exists without looking into it, so an update run from OpenWrt copied none of
# the vendor files into the image's own opt/mu300/android and lib/firmware (no modem, no Wi-Fi after the reboot).
# Nothing is written below a link of TO (find lists a directory before what is in it).
copy_missing() {
    ( cd "$1" ) || return 1
    ( cd "$1" && find . ! -name . ) | {
        skip=
        while IFS= read -r p; do
            case $p in "$skip"/*) continue ;; esac
            if [ -e "$2/$p" ] || [ -L "$2/$p" ]; then
                { [ -d "$2/$p" ] && [ ! -L "$2/$p" ]; } || skip=$p
                continue
            fi
            cp -a "$1/$p" "$2/$p" || exit 1
            skip=$p
        done
    }
}
# the directory the running system booted from (it stays in use under any name until the reboot)
is_root() { [ -d "$1" ] && [ / -ef "$1" ]; }
# the directory this system booted from; /etc/openwrt_release alone cannot tell the two OpenWrt systems apart
running_os() {
    # between apply and the reboot / is the kept copy: $n.old; between rollback (or apply --no-rollback) and the
    # reboot, $n.broken (without it a rolled-back openwrt-luci was "openwrt" here, and the Update page named the wrong
    # system: U30 Air, FINDINGS 86)
    for n in $SYSTEMS; do
        for d in "$DISK/$n" "$DISK/$n.old" "$DISK/$n.broken"; do
            [ -d "$d" ] && [ "${MU300_ROOT:-/}" -ef "$d" ] && { echo "$n"; return; }
        done
    done
    [ -e /etc/openwrt_release ] && echo openwrt || echo ubuntu
}

# systems present on the Linux partition
installed_systems() {
    for os in $SYSTEMS; do
        [ -d "$DISK/$os" ] && printf '%s ' "$os"
    done
}

latest_release() {
    fetch_stdout "${MU300_API_URL:-https://api.github.com/repos/$REPO}/releases/latest" \
        | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1
}

mounted_disk() {
    for n in $SYSTEMS; do [ -d "$DISK/$n" ] && return 0; done
    die "the Linux partition is not mounted at $DISK"
}

# notice: the note that a newer release is out. It is shown at login (Ubuntu: the motd, OpenWrt: /etc/profile.d)
# and at the top of mu300-toolkit. Nothing is ever installed by itself: an update that went wrong on a device
# nobody is watching could leave it unreachable.
NOTICE=${MU300_NOTICE:-/run/mu300/update-available}
MOTD_DIR=${MU300_MOTD_DIR:-/run/motd.d}
notice() {
    # an update that set something of the user's aside, or put something back, left a report (carry_report): a line
    # at login until "mu300-update report" has shown it (OpenWrt: /etc/profile.d/mu300-update.sh looks itself)
    if [ ! -e /etc/openwrt_release ] || [ -n "${MU300_MOTD_DIR:-}" ]; then
        if [ -e "${MU300_SYSROOT:-}/etc/mu300/update-report.new" ]; then
            mkdir -p "$MOTD_DIR" && chmod 755 "$MOTD_DIR" &&
                echo 'The last update set some of your files aside or put some back: sudo mu300-update report' > "$MOTD_DIR/61-mu300-update-report"
        else
            rm -f "$MOTD_DIR/61-mu300-update-report"
        fi
    fi
    latest=$(latest_release)
    [ -n "$latest" ] || return 1   # offline: the note stays as it was, the next round asks again
    inst=$(installed_version)
    mkdir -p "${NOTICE%/*}"
    # (newer: the release tags, docs/FINDINGS.md 125) a test release newer than the newest is no reason to note; a
    # system that is no release (unknown, a build of one's own) hears of every one
    if newer "$latest" "$inst" || { tag_ok "$latest" && ! tag_ok "$inst"; }; then
        printf 'mu300-linux %s is out (this is %s): sudo mu300-update apply\n' "$latest" "$inst" > "$NOTICE"
    else
        rm -f "$NOTICE"
    fi
    [ -e /etc/openwrt_release ] && [ -z "${MU300_MOTD_DIR:-}" ] && return 0
    mkdir -p "$MOTD_DIR" && chmod 755 "$MOTD_DIR"
    if [ -s "$NOTICE" ]; then cp "$NOTICE" "$MOTD_DIR/60-mu300-update"; else rm -f "$MOTD_DIR/60-mu300-update"; fi
}

# version: what is installed, without the network (mu300-toolkit's summary shows it)
version() {
    mounted_disk
    printf 'installed image   %s\n' "$(installed_version)"
    printf 'systems on disk   %s\n' "$(installed_systems_versions)"
    printf 'running now       %s\n' "$(running_os)"
    _xs=; for x in $(extra_installed); do extra_known "$x" && _xs="$_xs $x ($(extra_release "$x"))"; done
    printf 'extras           %s\n' "${_xs:- none (mu300-extra list)}"
    printf 'kernel            %s (boot image: %s; kernel choice %s)\n' "$(uname -r)" "$(cat "$BOOTDIR/installed.tag" 2>/dev/null || echo "from the installer")" "$(kernel_choice)"
}
# "openwrt v2026.10.18 ubuntu v2026.10.17": each system with the release its image came from
installed_systems_versions() {
    for os in $(installed_systems); do
        printf '%s %s ' "$os" "$(cat "$DISK/$os/etc/mu300/image-version" 2>/dev/null || echo unknown)"
    done
}
check() {
    mounted_disk
    latest=$(latest_release)
    [ -n "$latest" ] || die "could not reach GitHub ($(offline_why))"
    printf 'installed image   %s\n' "$(installed_version)"
    printf 'newest release    %s\n' "$latest"
    printf 'systems on disk   %s\n' "$(installed_systems)"
    printf 'running now       %s\n' "$(running_os)"
    _xs=; for x in $(extra_installed); do extra_known "$x" && _xs="$_xs $x ($(extra_release "$x"))"; done
    printf 'extras           %s\n' "${_xs:- none (mu300-extra list)}"
    printf 'kernel            %s (boot image: %s; kernel choice %s)\n' "$(uname -r)" "$(cat "$BOOTDIR/installed.tag" 2>/dev/null || echo "from the installer")" "$(kernel_choice)"
    ! _kn=$(kernel_retired "$(kernel_chosen)") ||
        printf 'kernel %s was chosen, and it is retired: the next update (mu300-update apply) installs %s instead\n' "$(kernel_chosen)" "$_kn"
    _up=${MU300_BIN:-/opt/mu300/bin}/mu300-user-packages
    [ ! -x "$_up" ] || [ ! -s "$CONF/user-packages/wanted" ] || printf 'your packages     %s\n' "$("$_up" brief)"
    for os in $(installed_systems); do
        [ -d "$DISK/$os.old" ] && printf 'rollback available for %s (%s)\n' "$os" "$(cat "$DISK/$os.old/etc/mu300/image-version" 2>/dev/null || echo unknown)"
    done
    # a device ahead of the newest release runs a test one (newer: docs/FINDINGS.md 125)
    if newer "$(installed_version)" "$latest"; then
        printf '\nThis is newer than the newest release (a test release); mu300-update apply --downgrade would go back to %s.\n' "$latest"
    elif [ "$(installed_version)" = "$latest" ] && [ "$(cat "$BOOTDIR/installed.tag" 2>/dev/null)" != "$latest" ]; then
        printf '\nThe system is up to date; the boot image may not be. Run: mu300-update apply\n'
    elif [ "$(installed_version)" = "$latest" ]; then
        printf '\nUp to date.\n'
    else
        printf '\nRun: mu300-update apply\n'
    fi
}

# everything that belongs to this device and must survive an update
# etc/unisoc-modem: the control panel's state (openwrt-luci; on Ubuntu the MU300 page's), above all lock-state.d, the
# network, band and cell locks it saved and replays at boot. The modem keeps a lock by itself; without this directory
# the panel came up after an update showing none, while the modem was still locked (FINDINGS 64).
# tools/android-install.sh has the same list.
# etc/crontabs: the jobs of OpenWrt's System > Scheduled Tasks (LuCI writes /etc/crontabs/root) and of every package
# or user that installs one. OpenWrt's sysupgrade keeps the directory; an update used to leave it behind in
# <os>.old, and the image's own /etc/crontabs is empty, so cron's init refused to start at all (FINDINGS 83).
keep_list() {
    case $(os_kind "$1") in
        ubuntu) echo "etc/mu300 etc/unisoc-modem etc/ssh etc/hostname etc/localtime etc/timezone etc/fstab home root srv usr/local var/lib/bluetooth" ;;
        openwrt) echo "etc/config etc/mu300 etc/unisoc-modem etc/dropbear etc/rc.local etc/crontabs root" ;;
    esac
}
# vendor files that the published images deliberately do not contain
vendor_list() {
    case $(os_kind "$1") in
        ubuntu) echo "opt/mu300/android usr/lib/firmware" ;;
        # lib/modules: the release only ships modules for the kernel it was built with, so a hand-built set for
        # another kernel (the experimental 6.18 port) would be thrown away by an update without this
        openwrt) echo "opt/mu300/android lib/firmware lib/modules" ;;
    esac
}

# Accounts are settings too, and /etc/shadow is not in keep_list: an update used to leave the image's own password
# (the well-known ubuntu/ubuntu, or OpenWrt's empty root) and drop the users added on the device. Take the old
# entry of every account both systems have (password hashes, group memberships merged), and bring over the users
# and groups the old system added (ids 1000-59999).
ACCOUNTS_MARK=/etc/.mu300-accounts-from-image   # in the images; removed once the accounts are the device's own
merge_accounts() {  # merge_accounts OLD_ROOT NEW_ROOT   ("" is the running system)
    o=$1 n=$2
    [ -f "$o/etc/shadow" ] && [ -f "$n/etc/shadow" ] || return 0
    for f in passwd group shadow gshadow; do
        [ -f "$o/etc/$f" ] && [ -f "$n/etc/$f" ] || continue
        awk -F: -v OFS=: -v f="$f" -v op="$o/etc/passwd" -v og="$o/etc/group" '
            BEGIN {
                while ((getline l < op) > 0) { split(l, a, ":"); if (a[3] >= 1000 && a[3] < 60000) lu[a[1]] = 1 }
                while ((getline l < og) > 0) { split(l, a, ":"); if (a[3] >= 1000 && a[3] < 60000) lg[a[1]] = 1 }
            }
            NR == FNR { old[$1] = $0; next }
            {
                seen[$1] = 1
                if ((f == "shadow" || f == "gshadow") && ($1 in old)) { print old[$1]; next }
                if (f == "group" && ($1 in old)) {
                    split(old[$1], og4, ":"); m = $4; k = split(og4[4], om, ",")
                    for (i = 1; i <= k; i++)
                        if (om[i] != "" && index("," m ",", "," om[i] ",") == 0) m = (m == "" ? om[i] : m "," om[i])
                    $4 = m
                }
                print
            }
            END {
                for (x in old) if (!(x in seen)) {
                    if ((f == "passwd" || f == "shadow") && (x in lu)) print old[x]
                    if ((f == "group" || f == "gshadow") && (x in lg)) print old[x]
                }
            }' "$o/etc/$f" "$n/etc/$f" > "$n/etc/$f.mu300" || { rm -f "$n/etc/$f.mu300"; return 1; }
        # renamed into place, never rewritten: a crash (or a reader at boot) never sees a half-written passwd.
        # The copy made with cp -p keeps the file's owner and mode (shadow is root:shadow 0640; no stat on OpenWrt).
        if [ -s "$n/etc/$f.mu300" ]; then
            cp -p "$n/etc/$f" "$n/etc/$f.mu300-new" && cat "$n/etc/$f.mu300" > "$n/etc/$f.mu300-new" && sync &&
                mv -f "$n/etc/$f.mu300-new" "$n/etc/$f" || { rm -f "$n/etc/$f.mu300" "$n/etc/$f.mu300-new"; return 1; }
        fi
        rm -f "$n/etc/$f.mu300"
    done
    rm -f "$n$ACCOUNTS_MARK"
}

# at boot (mu300-accounts): a system that an older mu300-update installed still has the image's accounts, and the
# system it replaced is still on the disk as <os>.old - take them from there before anyone can log in
accounts() {
    [ -e "$ACCOUNTS_MARK" ] || return 0
    os=$(running_os)
    if [ -f "$DISK/$os.old/etc/shadow" ]; then
        merge_accounts "$DISK/$os.old" "" && echo "accounts and passwords carried over from the previous $os"
    fi
    rm -f "$ACCOUNTS_MARK"
}

# --- user-packages begin
# Packages installed on the device are not in the release's image, and an update puts the image in place while it
# keeps /etc/config (OpenWrt) and /etc/mu300: their programs were gone and their settings stayed - OpenClash's left
# the device without DNS (#116). So before the switch the update writes down what was added - the packages asked for
# by hand (OpenWrt: /etc/apk/world; Ubuntu: dpkg's packages that apt did not pull in by itself) less the image's
# own set (etc/mu300/image-packages, written when the image is built) - into etc/mu300/user-packages/ of the new
# system, and sets the UCI files of those packages aside (etc/mu300/orphaned-config/): a package that is not there
# leaves no settings behind. At its first boot the new system installs them again (mu300-user-packages, a service)
# and puts their settings back. tools/android-install.sh (the installers' update) has a copy of this block; tests
# hold the two to one text. It runs on Android too: sh, awk, sed, grep, sort - nothing else, and safe under set -e.
UPK_DIR=etc/mu300/user-packages
UPK_ORPH=etc/mu300/orphaned-config
UPK_APKS=etc/mu300/user-apks
# what is never installed again: kernel modules (the feed's are for another kernel), and what the images take out on
# purpose (sysupgrade would flash the eMMC; ujail crash-loops services on 5.4)
upk_skip() {
    case $1 in
        kmod-*|kernel|procd-ujail|procd-seccomp|luci-app-attendedsysupgrade|attendedsysupgrade-common|owut) return 0 ;;
        linux-image-*|linux-modules-*|linux-headers-*|linux-generic*|linux-firmware) return 0 ;;
    esac
    return 1
}
upk_kind() { case $1 in ubuntu) echo ubuntu ;; *) echo openwrt ;; esac; }
# upk_dpkg ROOT [manual]: dpkg's installed packages in ROOT; with manual, less those apt installed as dependencies
# (what apt-mark showmanual says, read from the files: ROOT need not be the running system)
upk_dpkg() {
    [ -f "$1/var/lib/dpkg/status" ] || return 0
    { [ "${2:-}" != manual ] || cat "$1/var/lib/apt/extended_states" 2>/dev/null || :; echo '@dpkg'; cat "$1/var/lib/dpkg/status"; } |
        awk '$0 == "@dpkg" { s = 1; next }
             $1 == "Package:" { p = $2; next }
             !s && $1 == "Auto-Installed:" && $2 == 1 { auto[p] = 1; next }
             s && $1 == "Status:" && $3 == "ok" && $4 == "installed" { inst[p] = 1 }
             END { for (p in inst) if (!(p in auto)) print p }' | sort
}
# upk_manual ROOT KIND: the packages asked for by name (OpenWrt: the world file, versions and pins taken off)
upk_manual() {
    if [ "$2" = ubuntu ]; then upk_dpkg "$1" manual; return 0; fi
    [ -f "$1/etc/apk/world" ] || return 0
    sed 's/[<>=~@ ].*//' "$1/etc/apk/world" | awk 'NF' | sort -u
}
# upk_installed ROOT KIND: every installed package
upk_installed() {
    if [ "$2" = ubuntu ]; then upk_dpkg "$1"; return 0; fi
    [ -f "$1/lib/apk/db/installed" ] || return 0
    sed -n 's/^P://p' "$1/lib/apk/db/installed" | sort -u
}
# upk_txt_names FILE: the names in etc/mu300/packages.txt ("apk list --installed": name-version-rN arch ...)
upk_txt_names() {
    [ -f "$1" ] || return 0
    awk '{print $1}' "$1" | sed 's/-r[0-9][0-9]*$//; s/-[^-]*$//'
}
# upk_pending DIR: the packages of a record not installed again yet (nor given up on)
upk_pending() {
    [ -f "$1/wanted" ] || return 0
    { for _uf in done failed; do [ ! -f "$1/$_uf" ] || sed 's/^/x /' "$1/$_uf"; done; sed 's/^/w /' "$1/wanted"; } |
        awk '$1 == "x" { d[$2] = 1; next } NF > 1 && !($2 in d) { print $2 }'
}
# What belongs to the new image, not to the device, in the directories an update keeps: its version and package
# lists and its manifest in etc/mu300 (the old ones, carried over, made every update report the version it replaced), and
# the names of its own files in etc/config (never set aside). image_own_save NEW before the settings are copied,
# image_own_restore NEW after; upk_record removes what they keep in NEW/.mu300-image.
image_own_save() {
    rm -rf "$1/.mu300-image"; mkdir -p "$1/.mu300-image" || return 1
    for _uf in image-version image-packages packages.txt image-manifest.gz; do
        [ ! -f "$1/etc/mu300/$_uf" ] || cp "$1/etc/mu300/$_uf" "$1/.mu300-image/$_uf" || return 1
    done
    for _uf in "$1"/etc/config/*; do [ ! -e "$_uf" ] || echo "${_uf##*/}"; done > "$1/.mu300-image/config"
}
image_own_restore() {
    [ -d "$1/.mu300-image" ] || return 0
    mkdir -p "$1/etc/mu300" || return 1
    for _uf in image-version image-packages packages.txt image-manifest.gz; do
        if [ -f "$1/.mu300-image/$_uf" ]; then cp "$1/.mu300-image/$_uf" "$1/etc/mu300/$_uf" || return 1
        # a list of the old image would describe the wrong one (the version stays: "unknown" says less)
        elif [ "$_uf" != image-version ]; then rm -f "$1/etc/mu300/$_uf"; fi
    done
}
# upk_os_codename ROOT: Ubuntu's release name (noble, ...)
upk_os_codename() {
    sed -n 's/^VERSION_CODENAME=//p' "$1/usr/lib/os-release" 2>/dev/null | tr -d '"' | head -n 1
}
# upk_apt_keep OLD NEW [checked]: Ubuntu keeps only parts of /etc, and apt's sources were not among them: a PPA's
# packages could not come back. The source files added in etc/apt/sources.list.d are copied where the new image
# has no file of that name (the image's own are never replaced), with the keys they need: one in etc/apt/keyrings
# or usr/share/keyrings that a kept source names, and etc/apt/trusted.gpg.d's - each only where the new image has
# no file of that name. checked: the first boot tries apt-get update and disables a kept source that makes it fail
# (mu300-user-packages); without it (nothing to install again) a source of another Ubuntu release (24.04 -> 26.04)
# is copied disabled (NAME.disabled, which apt skips) and said so. NEW/.mu300-image/apt-kept: the sources kept on.
upk_apt_keep() {
    _ua=$2/.mu300-image/apt-kept _ul=
    : > "$_ua" || return 1
    _uoc=$(upk_os_codename "$1") _unc=$(upk_os_codename "$2")
    for _uf in "$1"/etc/apt/sources.list.d/*.list "$1"/etc/apt/sources.list.d/*.sources; do
        [ -f "$_uf" ] || continue
        _ur=etc/apt/sources.list.d/${_uf##*/}
        { [ ! -e "$2/$_ur" ] && [ ! -L "$2/$_ur" ]; } || continue
        mkdir -p "$2/etc/apt/sources.list.d" || return 1
        if [ -z "${3:-}" ] && [ "$_uoc" != "$_unc" ]; then
            cp -p "$_uf" "$2/$_ur.disabled" || return 1
            echo "  apt: /$_ur is for Ubuntu $_uoc, this is $_unc: kept disabled (/$_ur.disabled)"
        else
            cp -p "$_uf" "$2/$_ur" || return 1
            echo "$_ur" >> "$_ua"
            echo "  apt: /$_ur kept"
        fi
        _ul="$_ul $_uf"
    done
    [ -n "$_ul" ] || return 0
    # their pinning (etc/apt/preferences.d), where the new image has no file of that name; a pin whose source is
    # turned off later does nothing on its own (mu300-user-packages status names it). NEW/.mu300-image/apt-prefs.
    : > "$2/.mu300-image/apt-prefs" || return 1
    for _uf in "$1"/etc/apt/preferences.d/*; do
        [ -f "$_uf" ] || continue
        _ur=etc/apt/preferences.d/${_uf##*/}
        { [ ! -e "$2/$_ur" ] && [ ! -L "$2/$_ur" ]; } || continue
        mkdir -p "$2/etc/apt/preferences.d" && cp -p "$_uf" "$2/$_ur" || return 1
        echo "$_ur" >> "$2/.mu300-image/apt-prefs"
        echo "  apt: /$_ur kept"
    done
    # shellcheck disable=SC2086
    _us=$(cat $_ul 2>/dev/null)
    for _uf in "$1"/etc/apt/keyrings/* "$1"/usr/share/keyrings/* "$1"/etc/apt/trusted.gpg.d/*; do
        [ -f "$_uf" ] || continue
        _ur=${_uf#"$1"/}
        { [ ! -e "$2/$_ur" ] && [ ! -L "$2/$_ur" ]; } || continue
        case $_ur in
            etc/apt/trusted.gpg.d/*) ;;
            *) printf '%s\n' "$_us" | grep -qF "/$_ur" || continue ;;
        esac
        mkdir -p "$2/${_ur%/*}" && cp -p "$_uf" "$2/$_ur" || return 1
    done
}
# upk_units OLD: "PACKAGE UNIT enabled|disabled|masked" for the systemd units the packages named on stdin have in
# OLD (dpkg's file lists), as OLD had them - mu300-user-packages puts that back after it installs them again
upk_units() {
    while read -r _up; do
        for _ul in "$1/var/lib/dpkg/info/$_up.list" "$1/var/lib/dpkg/info/$_up":*.list; do
            [ -f "$_ul" ] || continue
            grep -E '^/(usr/)?lib/systemd/system/[A-Za-z0-9_.:-]+\.(service|socket|timer|path)$' "$_ul" |
                while read -r _uu; do
                    # an alias (a link to the unit, smartd.service) follows its unit
                    [ ! -L "$1$_uu" ] || continue
                    _uu=${_uu##*/}
                    case $_uu in *@*) continue ;; esac
                    _us=disabled
                    for _uw in "$1"/etc/systemd/system/*.wants/"$_uu" "$1"/etc/systemd/system/*.requires/"$_uu"; do
                        [ ! -L "$_uw" ] || _us=enabled
                    done
                    [ "$(readlink "$1/etc/systemd/system/$_uu" 2>/dev/null)" != /dev/null ] || _us=masked
                    echo "$_up $_uu $_us"
                done
        done
    done | sort -u
}
# upk_record OLD NEW OS: after the settings are in NEW, before the switch. Writes NEW/etc/mu300/user-packages/
# (wanted: the names; files: "package path" of their files in etc/; rc.d: the services enabled in OLD; from; state)
# and moves their etc/config files out of the way. MU300_KEEP_PACKAGES=0: they are not installed again (state
# skipped; mu300-user-packages retry does it later), their settings are set aside all the same.
upk_record() {
    _uo=$1 _un=$2 _uk=$(upk_kind "$3")
    _ut=$2/.mu300-image _ud=$2/$UPK_DIR
    mkdir -p "$_ut" || return 1
    # the old image's own set; a system from before that list: the new image's and the one packages.txt names
    if [ -s "$_uo/etc/mu300/image-packages" ]; then cat "$_uo/etc/mu300/image-packages"
    else
        cat "$_ut/image-packages" 2>/dev/null || :
        upk_manual "$_un" "$_uk"
        upk_txt_names "$_uo/etc/mu300/packages.txt"
    fi > "$_ut/not"
    upk_installed "$_un" "$_uk" >> "$_ut/not"
    # what an earlier update recorded and the device never got back (offline since, or skipped) stays wanted
    { upk_manual "$_uo" "$_uk"; upk_pending "$_uo/$UPK_DIR"; } > "$_ut/had"
    { sed 's/^/x /' "$_ut/not"; sed 's/^/w /' "$_ut/had"; } |
        awk '$1 == "x" { n[$2] = 1; next } NF > 1 && !($2 in n) { print $2 }' | sort -u > "$_ut/added"
    rm -rf "$_ud"
    : > "$_ut/wanted"
    while read -r _up; do upk_skip "$_up" || echo "$_up" >> "$_ut/wanted"; done < "$_ut/added"
    # Ubuntu: the apt sources added on the device (a PPA's packages cannot come back without it), see upk_apt_keep
    if [ "$_uk" = ubuntu ]; then
        upk_apt_keep "$_uo" "$_un" "$([ -s "$_ut/wanted" ] && echo checked)" || return 1
    fi
    if [ ! -s "$_ut/wanted" ]; then
        echo "  none: everything installed is part of the new image"
        rm -rf "$_ut"
        return 0
    fi
    mkdir -p "$_ud" || return 1
    mv "$_ut/wanted" "$_ud/wanted"
    [ ! -s "$_ut/apt-kept" ] || mv "$_ut/apt-kept" "$_ud/apt-sources"
    [ ! -s "$_ut/apt-prefs" ] || mv "$_ut/apt-prefs" "$_ud/apt-prefs"
    : > "$_ud/done"; : > "$_ud/failed"
    cat "$_uo/etc/mu300/image-version" > "$_ud/from" 2>/dev/null || echo unknown > "$_ud/from"
    # their files in etc/, from the package database of OLD (and of the record a pending one came from)
    if [ "$_uk" = openwrt ]; then
        { cat "$_uo/$UPK_DIR/files" 2>/dev/null || :
          [ ! -f "$_uo/lib/apk/db/installed" ] || awk '
            $0 ~ /^P:/ { p = substr($0, 3); next }
            $0 ~ /^F:/ { d = substr($0, 3); next }
            $0 ~ /^R:/ && (d == "etc" || d ~ /^etc\//) { print p " " d "/" substr($0, 3) }' "$_uo/lib/apk/db/installed"
        } | { sed 's/^/w /' "$_ud/wanted"; sed 's/^/f /'; } |
            awk '$1 == "w" { w[$2] = 1; next } ($2 in w) && NF > 2 { print substr($0, 3) }' | sort -u > "$_ud/files"
        for _uf in "$_uo"/etc/rc.d/*; do { [ -L "$_uf" ] || [ -e "$_uf" ]; } && echo "${_uf##*/}"; done > "$_ud/rc.d" || :
    else
        : > "$_ud/files"; : > "$_ud/rc.d"
        upk_units "$_uo" < "$_ud/wanted" > "$_ud/units"
    fi
    if [ "${MU300_KEEP_PACKAGES:-1}" = 0 ]; then echo skipped > "$_ud/state"; else echo pending > "$_ud/state"; fi
    echo "  $(tr '\n' ' ' < "$_ud/wanted")"
    # a package the feeds do not have, coming back from the file kept for it before the update (mu300-user-packages keep)
    [ ! -f "$_uo/$UPK_APKS/index" ] || while read -r _kp _kv _kf; do
        [ ! -f "$_uo/$UPK_APKS/$_kf" ] || ! grep -qxF "$_kp" "$_ud/wanted" || echo "  from a kept file: /$UPK_APKS/$_kf"
    done < "$_uo/$UPK_APKS/index"
    if [ "$(cat "$_ud/state")" = skipped ]; then
        echo "  The new system does not have them, and they are not installed again (MU300_KEEP_PACKAGES=0 or"
        echo "  --no-reinstall; later: mu300-user-packages retry)."
    else
        echo "  The new system does not have them: its first boot installs them again once the device is online"
        echo "  (the result: mu300-user-packages status)."
    fi
    # their UCI files: a package that is not there must leave nothing behind that acts on the network. Only a file
    # its package owns, in etc/config, that the new image does not have itself (dhcp, firewall, luci: never).
    _um=
    while read -r _up _uf; do
        case $_uf in etc/config/?*) ;; *) continue ;; esac
        { [ -f "$_un/$_uf" ] && [ ! -L "$_un/$_uf" ]; } || continue
        ! grep -qxF "${_uf#etc/config/}" "$_ut/config" 2>/dev/null || continue
        mkdir -p "$_un/$UPK_ORPH/etc/config" && mv -f "$_un/$_uf" "$_un/$UPK_ORPH/$_uf" || return 1
        [ -n "$_um" ] || echo "  Their settings are set aside until they are back, so that they cannot act without them:"
        echo "    /$_uf -> /$UPK_ORPH/$_uf ($_up)"
        _um=1
    done < "$_ud/files"
    rm -rf "$_ut"
}
# stale_config_clean NEW: what the images of v2026.10.18 left in etc/config and an update then copied onto every
# device (the config files of the image are added to the kept ones): attendedsysupgrade, of a package the images
# remove on purpose, and the .apk-new copies apk leaves beside a changed config. Gone from NEW's etc/config unless
# the package is installed there (attendedsysupgrade stays with attendedsysupgrade-common or its LuCI app).
stale_config_clean() {
    for _uf in "$1"/etc/config/*.apk-new; do [ ! -e "$_uf" ] || rm -f "$_uf"; done
    [ -e "$1/etc/config/attendedsysupgrade" ] || return 0
    upk_installed "$1" openwrt | grep -qx 'attendedsysupgrade-common\|luci-app-attendedsysupgrade' && return 0
    rm -f "$1/etc/config/attendedsysupgrade"
}
# --- user-packages end
# --- carry begin
# An update keeps everything the user made (docs/FINDINGS.md 85). Until v2026.10.27 it kept a list of places
# (keep_list) and the image replaced the rest: /etc/wireguard, a unit written by hand, crontabs, /var/lib/docker,
# /opt, a changed /etc/sysctl.conf were gone from the system after an update. Now the question is asked the other
# way round: which files of the old system came with its image? Its manifest says (one line per file of the image,
# with type, mode, owner, size and sha256: an image carries its own as etc/mu300/image-manifest.gz, and the ones of
# the releases before that ship in opt/mu300/lib/image-manifests). Everything else is the user's and goes into the
# new system; an image file the user changed goes too, by the rules below. What cannot go where it was is set aside
# under /etc/mu300/update-kept/<old release>/ (user/: the user's version, image/: the release's) and named in
# /etc/mu300/update-report - nothing is dropped without a line there.
#   not the image's (made by the user, or by software they installed)
#       carried to its place. Where the new image has a file of that name: under /etc /var /home /root /srv /usr/local
#       /opt /mnt /media the user's is used and the release's set aside; elsewhere, and where the release has a
#       directory, the release's is used and the user's set aside.
#   the image's, changed by the user
#       /etc /var /home /root /srv /usr/local /opt /mnt /media: the user's version is used; when the new release
#       changed that file too, its version is set aside (image/). Elsewhere (/usr, /bin, /lib, /www: programs) the
#       release's is used and the user's set aside (user/) - as for the project's own programs (opt/mu300,
#       usr/libexec/unisoc-modem, the mu300-* units and init scripts, the commands in /usr/local/bin), for scripts of
#       packages in /etc/init.d and /etc/hotplug.d, for /etc/pam.d/common-* (written by pam-auth-update for the
#       packages that are there) and for the image's own apt sources. Every such case is a line of the report.
#   never less protected than the user left it
#       What the user tightened stays in force, whatever the rule above says about the file. Settings are all under
#       the user's directories (adb, sshd and dropbear, the firewall, the VPN and its kill switch, sudoers, sysctl,
#       the panel's users and TLS: /etc/mu300, /etc/ssh, /etc/config, ...). A service the user turned off stays off:
#       an enable link that is gone stays gone (also of the project's own services, and without a manifest: a link
#       of the new image for a service the old system had and did not enable), and a mask (a link to /dev/null) is
#       the user's even over the project's own unit. A mode the user narrowed is put on the new image's file even
#       where the release's content is used. A package the user removed is back with the image, and its services are
#       as the old system had them: a service it did not run is not enabled, while one another package provided (and
#       the old system ran) stays on. An account of the image that the old system did not have (the user deleted it,
#       or the release added it) is locked.
#   the image's, deleted by the user
#       under /etc /home /root /srv /usr/local /opt /mnt /media it stays deleted, and so does a service's enable link
#       (rc.d, *.wants) - unless it is one of the project's own programs, a script in /etc/init.d or /etc/hotplug.d,
#       went with an upgrade of its package, or its package was removed and is part of the image again: those are
#       back, and the report says so. A uci-defaults script removes itself when it ran, and must run again in the
#       new system. Elsewhere the release's file is back.
#   the package manager's (its databases, the files of packages, /etc/alternatives)
#       never carried file by file: the packages added on the device are installed again at the first boot
#       (user-packages above). A package's configuration file is carried as the user's; its data is in no package and
#       is carried like everything else. A file a package upgrade changed (dpkg's and apk's own sums say so) is not
#       the user's.
#   never carried
#       what is below /proc /sys /dev /run /tmp /var/tmp /var/cache, sockets, what is on another filesystem (a mount
#       point is carried as the directory it is; mu300-carry never leaves the filesystem), Ubuntu's kernel modules
#       (they come from the kernel bundle), /etc/ld.so.cache and Python's caches under /usr.
# Accounts and owners: merge_accounts, and here the system accounts added on the device. A file belongs to an
# account, not to a number (carry_accounts_plan): the name the old system has for the owner decides, the accounts
# are settled before a file is carried, and a file never becomes another account's by its number.
# Without a manifest (an image built by hand, a release from before v2026.09.21): everything the new image does not
# have is carried, keep_list's places are the user's as before, and of the rest every file that differs from the new
# image's is set aside (user/) while there is room - which is the old image's own or the user's change cannot be told.
#
# One implementation for the three ways to update: this block runs from the NEW image, by its static busybox
# (carry_run: "busybox sh NEW/opt/mu300/bin/mu300-update carry OLD NEW OS MODE"), on the device and under Android
# alike, with the image's mu300-carry for the files (tools/carry/mu300-carry.c). MODE copy: OLD stays whole and
# apart, for a rollback. MODE link: files become second names of OLD's, no data is copied - for an update that does
# not keep OLD (the installers', and apply --no-rollback). OLD is never written to.
CARRY_KEPT=etc/mu300/update-kept
CARRY_REPORT=etc/mu300/update-report
CARRY_TAB=$(printf '\t')
carry_bb() {  # carry_bb NEW: the static busybox of the image
    for _cb in "$1/usr/bin/busybox" "$1/opt/mu300/bin/busybox"; do
        if [ -f "$_cb" ] && [ ! -L "$_cb" ] && [ -x "$_cb" ]; then echo "$_cb"; return 0; fi
    done
    return 1
}
# carry_ready NEW: the image brings all of it - this block, mu300-carry and a busybox - and they run here
carry_ready() {
    _cb=$(carry_bb "$1") || return 1
    [ -x "$1/opt/mu300/bin/mu300-carry" ] && grep -q '^# --- carry begin' "$1/opt/mu300/bin/mu300-update" 2>/dev/null || return 1
    "$_cb" true 2>/dev/null || return 1
    "$1/opt/mu300/bin/mu300-carry" scan "$1/opt/mu300/lib" >/dev/null 2>&1
}
# carry_run OLD NEW OS MODE: 0 done; 3 not enough room (said); anything else failed, and NEW is not to be used.
# Done is what carry_system says at its very end, with NEW/.mu300-carried: a run that ended without it did not do
# the work, whatever its status (MU300_LIB in the environment would make the script define its functions and leave).
carry_run() {
    rm -f "$2/.mu300-carried"
    MU300_LIB='' "$(carry_bb "$2")" sh "$2/opt/mu300/bin/mu300-update" carry "$1" "$2" "$3" "$4" || return
    [ -e "$2/.mu300-carried" ] || return 1
    rm -f "$2/.mu300-carried"
}
# carry_unesc LINE: the path a list line names (a backslash is written \\, a newline \n)
carry_unesc() { _cu=$(printf '%bx' "$1"); printf '%s' "${_cu%x}"; }
# carry_image OLD OS: the name of the image a system came from (ubuntu-24.04, ubuntu-26.04, openwrt, openwrt-luci)
carry_image() {
    case $2 in
        ubuntu) echo "ubuntu-$(sed -n 's/^VERSION_ID="\(.*\)"/\1/p' "$1/usr/lib/os-release" 2>/dev/null | head -n 1)" ;;
        *) echo "$2" ;;
    esac
}
# carry_manifest OLD NEW OS TAG OUT: the manifest of OLD's image into OUT (its lines, without the first); status 1
# when there is none. TAG is what OLD says it is, read once by the caller: the manifest that is looked for, checked
# and used is the one of that release and of that image, and no other. The file is copied once into the working
# directory (root's alone) and only that copy is checked and read - never the file in OLD a second time. OLD's own
# manifest counts when its first line names this image and TAG; else the one the new image has for them. Every line
# must be a manifest line with a path that stays in the system: one that is not refuses the whole manifest, and the
# update goes on as without one.
carry_manifest() {
    case $4 in ''|unknown|*[!0-9A-Za-z._-]*) return 1 ;; esac
    _ci=$(carry_image "$1" "$3")
    case $_ci in ''|*[!0-9A-Za-z._-]*) return 1 ;; esac
    rm -f "$5" "$5.gz"
    _cm=$1/etc/mu300/image-manifest.gz
    if [ -f "$_cm" ] && [ ! -L "$_cm" ] && cat "$_cm" > "$5.gz" 2>/dev/null && gzip -t "$5.gz" 2>/dev/null &&
        gzip -dc "$5.gz" | awk -v want="mu300-image-manifest 1 $_ci $4" 'NR == 1 { if ($0 != want) exit 1; next } { print }
            END { if (NR < 2) exit 1 }' > "$5" && carry_manifest_ok "$5"; then
        rm -f "$5.gz"
        return 0
    fi
    rm -f "$5" "$5.gz"
    _cm=$2/opt/mu300/lib/image-manifests/$_ci.gz
    [ -f "$_cm" ] && [ ! -L "$_cm" ] && cat "$_cm" > "$5.gz" 2>/dev/null && gzip -t "$5.gz" 2>/dev/null || { rm -f "$5.gz"; return 1; }
    gzip -dc "$5.gz" | awk -v tag="$4" -v image="$_ci" '
        NR == 1 { if ($1 != "mu300-image-manifests" || $2 != 1 || $3 != image) { bad = 1; exit }; next }
        NR == 2 { n = -1; for (i = 2; i <= NF; i++) if ($i == tag) n = i - 2; if (n < 0) { bad = 1; exit }; next }
        {
            k = split($1, r, ",")
            for (i = 1; i <= k; i++) {
                a = r[i]; b = a; d = index(a, "-")
                if (d > 0) { b = substr(a, d + 1); a = substr(a, 1, d - 1) }
                if (n >= a + 0 && n <= b + 0) { print substr($0, index($0, " ") + 1); break }
            }
        }
        END { exit (bad || NR < 3) ? 1 : 0 }' > "$5" && carry_manifest_ok "$5" || { rm -f "$5" "$5.gz"; return 1; }
    rm -f "$5.gz"
}
# carry_manifest_ok FILE: every line is "TYPE MODE UID GID SIZE HASH PATH" with a relative path without . or .. parts
carry_manifest_ok() {
    [ -s "$1" ] && awk '
        { p = $0; for (i = 0; i < 6; i++) p = substr(p, index(p, " ") + 1) }
        NF < 7 || $1 !~ /^[fdlcbp]$/ || $2 !~ /^[0-7]+$/ || $3 !~ /^[0-9]+$/ || $4 !~ /^[0-9]+$/ || $5 !~ /^[0-9]+$/ ||
            ($6 != "-" && $6 !~ /^[0-9a-f]+$/) || p ~ /^\// || ("/" p "/") ~ /\/\.\.?\// || ("/" p "/") ~ /\/\// { exit 1 }' "$1"
}
# carry_pkgdb ROOT KIND O C S: what the package manager of ROOT says, one record per line, tabs between the fields:
#   O package path      a path of a package (dpkg: info/*.list; apk: the F: and R: lines of its database)
#   C path              a configuration file of a package (dpkg: Conffiles; apk: packages/*.conffiles, where a name
#                       with / at its end is everything below)
#   S algo:sum path     what the package manager installed there (dpkg: md5, apk: Q1 and sha1 in base64)
# O, C, S: the letters to write (the old and the new system get their own); S "" leaves the sums out.
carry_pkgdb() {
    if [ "$2" = ubuntu ]; then
        [ -d "$1/var/lib/dpkg/info" ] || return 0
        # dpkg lists /bin/ls where the file is /usr/bin/ls: the top directories that are links (usrmerge)
        _cm=
        for _cd in bin sbin lib lib32 lib64 libx32; do [ ! -L "$1/$_cd" ] || _cm="$_cm $_cd"; done
        for _cx in list md5sums; do
            [ "$_cx" = list ] || [ -n "$5" ] || continue
            find "$1/var/lib/dpkg/info" -maxdepth 1 -type f -name "*.$_cx" 2>/dev/null | LC_ALL=C sort > "$CARRY_T/pkg.files"
            [ -s "$CARRY_T/pkg.files" ] || continue
            # (xargs: more files than one command line takes)
            xargs awk -v o="$3" -v s="$5" -v merged="$_cm" -v ext="$_cx" '
                BEGIN { k = split(merged, m, " "); for (i = 1; i <= k; i++) um[m[i]] = 1 }
                function real(p,   top) {
                    sub(/^\.?\//, "", p)
                    top = p; sub(/\/.*/, "", top)
                    return (top in um) ? "usr/" p : p
                }
                FNR == 1 { pkg = FILENAME; sub(/.*\//, "", pkg); sub(/\.[a-z0-9]*$/, "", pkg); sub(/:.*/, "", pkg) }
                ext == "list" { if ($0 != "/." && $0 != "") print o "\t" pkg "\t" real($0); next }
                { print s "\tmd5:" substr($0, 1, 32) "\t" real(substr($0, 35)) }' < "$CARRY_T/pkg.files" || return 1
        done
        [ ! -f "$1/var/lib/dpkg/status" ] || awk -v c="$4" -v s="$5" -v merged="$_cm" '
            BEGIN { k = split(merged, m, " "); for (i = 1; i <= k; i++) um[m[i]] = 1 }
            function real(p,   top) { sub(/^\//, "", p); top = p; sub(/\/.*/, "", top); return (top in um) ? "usr/" p : p }
            /^Conffiles:/ { inc = 1; next }
            inc && /^ / { print c "\t" real($1); if (s != "" && length($2) == 32) print s "\tmd5:" $2 "\t" real($1); next }
            { inc = 0 }' "$1/var/lib/dpkg/status" || return 1
        return 0
    fi
    [ ! -f "$1/lib/apk/db/installed" ] || awk -v o="$3" -v s="$5" '
        /^P:/ { pkg = substr($0, 3); next }
        /^F:/ { dir = substr($0, 3); if (dir != "") print o "\t" pkg "\t" dir; next }
        /^R:/ { file = (dir == "" ? "" : dir "/") substr($0, 3); print o "\t" pkg "\t" file; next }
        /^Z:/ { if (s != "" && file != "") print s "\tq1:" substr($0, 3) "\t" file; next }
        /^$/ { file = "" }' "$1/lib/apk/db/installed" || return 1
    for _cf in "$1"/lib/apk/packages/*.conffiles "$1"/lib/apk/packages/*.conffiles_static; do
        [ -f "$_cf" ] || continue
        sed -n "s|^/\(..*\)|$4$CARRY_TAB\1|p" "$_cf"
    done
    return 0
}
# carry_pksame OLD < "algo:sum<TAB>path" lines: the paths whose file in OLD is the one the package manager put there
carry_pksame() {
    while IFS= read -r _cl; do
        _cs=${_cl%%"$CARRY_TAB"*}; _cp=${_cl#*"$CARRY_TAB"}
        _cf=$1/$(carry_unesc "$_cp")
        [ -f "$_cf" ] && [ ! -L "$_cf" ] || continue
        case $_cs in
            md5:*) _ch=$(md5sum < "$_cf" 2>/dev/null | cut -c1-32) ;;
            q1:*) _ch=Q1$(sha1sum < "$_cf" 2>/dev/null | cut -c1-40 | xxd -r -p 2>/dev/null | base64 2>/dev/null) ;;
            *) continue ;;
        esac
        [ "${_cs#*:}" != "$_ch" ] || printf '%s\n' "$_cp"
    done
    return 0
}
# The plan. carry_plan PASS: reads the scan of OLD on stdin, and from $CARRY_T what there is of: manifest (OLD's
# image), pkg (carry_pkgdb of OLD and NEW, and "I package" for those installed in OLD), scan.new, sum.old and sum.new
# ("HASH PATH", mu300-carry sum), pksame, cmds (the commands the images link into /usr/local/bin).
#   pass 1 and 2 write what must be hashed before the next one can decide: "O path" (in OLD), "N path" (in NEW),
#   "K algo:sum path" (is OLD's file the package manager's?);
#   pass 3 writes the plan, tabs between the fields:
#     L path           carry it to its place                  H path          set the user's aside (update-kept/user)
#     S path           set the release's aside first (image)  R path          remove it from NEW first
#     M mode uid gid path   give NEW's the owner and mode the user gave it
#     A path           an apt source added on the device (upk_apt_keep decides about it, see carry_system)
#     n blocks kind    512-byte blocks to be written (kind l, h or s)      c files package-files
#     r code path      a line of the report (carry_report has the words)
carry_plan() {
    awk -v pass="$1" -v T="$CARRY_T" -v kind="$CARRY_KIND" -v keep="$CARRY_KEEP" -v fb="$CARRY_FALLBACK" '
    function rest(s, n,   i) { for (i = 0; i < n; i++) s = substr(s, index(s, " ") + 1); return s }
    function f(l, n,   a) { split(l, a, " "); return a[n] }
    function parent(p) { return match(p, /\/[^\/]*$/) ? substr(p, 1, RSTART - 1) : "" }
    function under(p, re) { return p ~ ("^(" re ")/") }
    function never(p) {
        if (under(p, "proc|sys|dev|run|tmp|var/tmp|var/cache|var/run|var/lock|lost\\+found|mnt/mu300-disk")) return 1
        if (kind == "ubuntu" && under(p, "usr/lib/modules")) return 1
        if (p ~ /^usr\/.*\/__pycache__(\/|$)/ && p !~ /^usr\/local\//) return 1
        return p ~ /^\.mu300-(image|carry)(\/|$)/
    }
    # handled by another step of the update, or the state of the package manager: never by this plan
    function other(p) {
        if (p ~ /^etc\/(passwd|group|shadow|gshadow|subuid|subgid)-?$/ || p == "etc/.pwd.lock" || p == "etc/ld.so.cache") return 1
        if (p ~ /^etc\/mu300\/(image-version|image-packages|packages\.txt|image-manifest\.gz|update-report\.new)$/) return 1
        if (p == "etc/.mu300-accounts-from-image" || p ~ /^etc\/mu300\/user-packages(\/|$)/ || p == "etc/apk/world") return 1
        return p ~ /^(var\/lib\/dpkg|var\/lib\/apt|var\/lib\/ucf|var\/lib\/pam|etc\/alternatives|lib\/apk|usr\/lib\/opkg)(\/|$)/ ||
               p ~ /^var\/lib\/systemd\/deb-systemd-(user-)?helper-/
    }
    # apt sources: the ones added on the device are kept by upk_apt_keep (on, or off for another Ubuntu release)
    function aptsrc(p) { return p ~ /^etc\/apt\/sources\.list\.d\/[^\/]*\.(list|sources)$/ }
    function vendor(p) {
        return under(p, "opt/mu300/android|lib/firmware|usr/lib/firmware") || (kind == "openwrt" && under(p, "lib/modules"))
    }
    function project(p,   b) {
        if (under(p, "opt/mu300|usr/libexec/unisoc-modem")) return 1
        if (p ~ /^(etc|usr\/lib|lib)\/systemd\/system\/mu300-[^\/]*$/ || p ~ /^etc\/init\.d\/mu300-[^\/]*$/) return 1
        if (p ~ /^usr\/local\/bin\/[^\/]*$/) { b = p; sub(/.*\//, "", b); return (b in cmds) }
        return 0
    }
    # programs under /etc: the scripts that start and wire the services
    function script(p) { return under(p, "etc/init\\.d|etc/hotplug\\.d|etc/hotplug-preinit\\.d|etc/rc\\.button|etc/board\\.d") }
    # a unit the user masked (a link to /dev/null where its name is looked up first): the user turned it off
    function ismask(p) { return t == "l" && size == 9 && p ~ /^etc\/systemd\/(system|user)\/[^\/]*$/ }
    # every permission bit of mode A is one of mode B, and they are not the same: A is the narrower
    function narrower(a, b,   i, k, x, y) {
        if (a == b) return 0
        a = sprintf("%04d", a); b = sprintf("%04d", b)
        for (i = 1; i <= 4; i++) {
            x = substr(a, i, 1) + 0; y = substr(b, i, 1) + 0
            for (k = 4; k >= 1; k = int(k / 2)) if (int(x / k) % 2 > int(y / k) % 2) return 0
        }
        return 1
    }
    function listed(arr, p,   d) {
        if (p in arr) return 1
        for (d = parent(p); d != ""; d = parent(d)) if ((d "/") in arr) return 1
        return 0
    }
    function userarea(p) { return under(p, "etc|var|home|root|srv|mnt|media|usr/local|opt") }
    # the version of the user is the one in use (else the one of the release is)
    function wins(p) {
        if (ismask(p)) return 1
        if (!userarea(p) || project(p) || aptsrc(p) || p ~ /^etc\/pam\.d\/common-/) return 0
        # a script of a package (init.d, hotplug.d) is a program, not a setting
        if (t == "f" && script(p) && (p in owned) && !listed(conf, p) && (!(p in om) || om[p] ~ /^f /)) return 0
        return 1
    }
    function quiet(p) { return under(p, "var") }
    function enable_link(p) {
        return p ~ /^etc\/rc\.d\/[SK][^\/]*$/ || p ~ /^etc\/systemd\/(system|user)\/[^\/]*\.(wants|requires)\/[^\/]*$/
    }
    function service_file(p) { return p ~ /^((usr\/)?lib|etc)\/systemd\/system\/[^\/]*$/ || p ~ /^etc\/init\.d\/[^\/]*$/ }
    # the service an enable link is for: the unit of a wants link, the init script of S50cron
    function service_of(p,   b) { b = p; sub(/.*\//, "", b); if (p ~ /^etc\/rc\.d\//) sub(/^[SK][0-9]*/, "", b); return b }
    # same: the image file as it came; meta: its content, but another owner or mode; mod: changed; new: not of the image
    function state(p,   m, ty) {
        if (!(p in om)) return "new"
        m = om[p]; ty = (t == "m") ? "d" : t
        if (f(m, 1) != ty) return "mod"
        if (ty == "f" && (f(m, 5) != size || !(p in so) || so[p] != f(m, 6))) return "mod"
        if (ty == "l" && (!(p in so) || so[p] != f(m, 6))) return "mod"
        if (f(m, 3) != uid || f(m, 4) != gid || (ty != "l" && f(m, 2) != mode)) return "meta"
        return "same"
    }
    function hashable(a, b) { return a == b && (a == "f" || a == "l") }
    function same_as_new(p) {
        if (!(p in ns) || f(ns[p], 1) != t) return 0
        if (t == "f") return f(ns[p], 5) == size && (p in so) && (p in sn) && so[p] == sn[p]
        if (t == "l") return (p in so) && (p in sn) && so[p] == sn[p]
        return t != "d"
    }
    function new_is_old_image(p,   m) {
        m = om[p]
        if (f(m, 1) != f(ns[p], 1)) return 0
        if (f(m, 1) == "f") return f(m, 5) == f(ns[p], 5) && (p in sn) && sn[p] == f(m, 6)
        if (f(m, 1) == "l") return (p in sn) && sn[p] == f(m, 6)
        return 1
    }
    function want(code, p) { if (!((code p) in asked)) { asked[code p] = 1; print code "\t" p } }
    function note(code, p) { print "r\t" code "\t" p }
    # the number has no name in the old system, and an account of the new one has it
    function foreign() { return (!(("u" uid) in oldid) && (("u" uid) in newid)) || (!(("g" gid) in oldid) && (("g" gid) in newid)) }
    function live(p) {
        if (foreign()) { hold(p, "o"); if (t == "d") block = p; return }
        # the files of the device itself (firmware, the userspace of Android) are not of the user and nothing
        # writes them in place: second names of the files of the old system in every mode, never a copy (205 MiB
        # on an F50)
        if (t == "f" && vendor(p)) { print "V\t" p; files++; return }
        print "L\t" p; if (t != "d") { nl += blocks; files++ }
    }
    function hold(p, why) {
        print "H\t" p; nh += blocks
        if (why != "") note(why, p)
        # the content is the one of the release; a mode the user narrowed (0600, no execute bit) stays narrowed
        if (t == "f" && (p in ns) && f(ns[p], 1) == "f" && narrower(mode, f(ns[p], 2)))
            print "M\t" mode " " f(ns[p], 3) " " f(ns[p], 4) "\t" p
    }
    function save(p) { if (f(ns[p], 1) != "d") { print "S\t" p; nsv += f(ns[p], 8) } }
    # the owner and mode the user gave an image file: theirs in their directories; elsewhere a narrower mode is
    # kept (never a wider one, never another owner: the release decides who runs its programs)
    function meta(p) {
        if (t == "l" || nt != t) return
        if (wins(p) && !foreign()) print "M\t" mode " " ((("u" uid) in idm) ? idm["u" uid] : uid) " " ((("g" gid) in idm) ? idm["g" gid] : gid) "\t" p
        else if (narrower(mode, f(ns[p], 2))) print "M\t" mode " " f(ns[p], 3) " " f(ns[p], 4) "\t" p
        else if (mode != f(ns[p], 2) || uid != f(ns[p], 3) || gid != f(ns[p], 4)) note("m", p)
    }
    # no manifest: which file is the own of the old image cannot be told
    function fallback(   k) {
        if (aptsrc(p) && !innew) { if (pass == 3) print "A\t" p; return }
        if (pass == 1) { if (innew && hashable(t, nt) && (t == "l" || f(ns[p], 5) == size)) { want("O", p); want("N", p) }; return }
        if (pass == 2) { if (innew && t == "f" && (p in psum) && !same_as_new(p)) want("K\t" psum[p], p); return }
        # the version of the user wins: the places an update always kept, and what protects the device
        k = ismask(p) || (((keep != "" && p ~ ("^(" keep ")(/|$)")) || p ~ secure) && !project(p) && !script(p) && p !~ /^etc\/pam\.d\/common-/)
        if (t == "m") t = "d"
        if (t == "d") {
            if (innew && nt == "d") return
            if (innew) { if (k) { print "R\t" p; live(p) } else { block = p; hold(p, "i") }; return }
            if (p in owned) return
            if (project(p) && !vendor(p)) { block = p; hold(p, "f"); return }
            live(p)
            return
        }
        if (!innew) {
            if (vendor(p)) { live(p); return }
            if ((p in owned) && !listed(conf, p)) { npkg++; return }
            if (project(p)) { hold(p, "f"); return }
            live(p)
            return
        }
        if (same_as_new(p)) {
            # the same file: a mode the user narrowed stays narrowed
            if (t == "f" && narrower(mode, f(ns[p], 2))) print "M\t" mode " " f(ns[p], 3) " " f(ns[p], 4) "\t" p
            return
        }
        if (vendor(p) || (p in pksame)) return
        if (nt == "d") { hold(p, "i"); return }
        if (k) { live(p); return }
        hold(p, "f")
    }
    BEGIN {
        secure = "^etc/(config|sudoers|sudoers\\.d|sysctl\\.conf|sysctl\\.d|nftables\\.conf|nftables\\.d|firewall\\.user|security|hosts\\.allow|hosts\\.deny|pam\\.d|modprobe\\.d|ssl/private|uhttpd\\.crt|uhttpd\\.key|rc\\.local|systemd/system|systemd/user|rc\\.d|crontabs|cron\\.d)(/|$)"
        while ((getline l < (T "/manifest")) > 0) om[rest(l, 6)] = l
        close(T "/manifest")
        while ((getline l < (T "/pkg")) > 0) {
            c = substr(l, 1, 1); l = substr(l, 3)
            if (c == "C") { conf[l] = 1; continue }
            if (c == "D") continue
            if (c == "I") { inst[l] = 1; continue }
            a = substr(l, 1, index(l, "\t") - 1); l = substr(l, index(l, "\t") + 1)
            if (c == "O") owned[l] = a; else if (c == "N") nown[l] = a; else if (c == "S") psum[l] = a
        }
        close(T "/pkg")
        while ((getline l < (T "/scan.new")) > 0) ns[rest(l, 8)] = l
        while ((getline l < (T "/sum.old")) > 0) so[rest(l, 1)] = f(l, 1)
        while ((getline l < (T "/sum.new")) > 0) sn[rest(l, 1)] = f(l, 1)
        while ((getline l < (T "/pksame")) > 0) pksame[l] = 1
        while ((getline l < (T "/cmds")) > 0) cmds[l] = 1
        while ((getline l < (T "/ids")) > 0) { split(l, q, " "); if (substr(q[1], 1, 1) == "o") oldid[substr(q[1], 2) q[2]] = 1; else newid[substr(q[1], 2) q[2]] = 1 }
        while ((getline l < (T "/idmap")) > 0) { split(l, q, " "); idm[q[1] q[2]] = q[3] }
    }
    {
        t = $1; mode = $2; uid = $3; gid = $4; size = $5; blocks = $8; p = rest($0, 8)
        if (p in om) seen[p] = 1
        if (fb && (enable_link(p) || service_file(p) || p ~ /^etc\/sudoers\.d\//)) had[p] = 1
        if (block != "") {
            if (index(p, block "/") == 1) {
                # below a directory that cannot be there: what is not the image there is set aside
                if (pass == 3 && t != "s" && !never(p) && !other(p) && !vendor(p) && (fb || state(p) != "same") &&
                    !(!(p in om) && (p in owned) && !listed(conf, p))) {
                    if (blocknote != "") { note(blocknote, block); blocknote = "" }
                    hold(p, "")
                }
                next
            }
            block = ""; blocknote = ""
        }
        if (t == "s" || never(p) || other(p)) next
        innew = (p in ns); nt = innew ? f(ns[p], 1) : ""
        if (fb) { fallback(); next }
        if (pass == 1) {
            if ((p in om) && hashable(t, f(om[p], 1)) && (t == "l" || f(om[p], 5) == size)) want("O", p)
            next
        }
        st = state(p)
        if (t == "m") t = "d"
        if (pass == 2) {
            if (st == "same" || st == "meta") next
            if (st == "mod" && (p in psum) && t == "f") want("K\t" psum[p], p)
            if (!innew) next
            if (nt == "f" || nt == "l") want("N", p)
            if (hashable(t, nt) && (t == "l" || f(ns[p], 5) == size)) want("O", p)
            next
        }
        if (t == "d") {
            mine = (st == "mod" || (st == "new" && !(p in owned)))
            if (innew && nt != "d") {
                # the release has a file or a link where the old system has a directory
                if (mine && wins(p)) { save(p); print "R\t" p; live(p); note("u", p) }
                else if (mine) { block = p; hold(p, "i") }
                else { block = p; blocknote = "x" }
                next
            }
            if (mine && !innew) live(p)
            else if (st == "meta" && innew) meta(p)
            next
        }
        if (st == "same") next
        if (st == "meta") { if (innew) meta(p); next }
        if (aptsrc(p)) { if (st == "mod" && !same_as_new(p)) hold(p, "i"); else if (st == "new") print "A\t" p; next }
        if (st == "new") {
            if (vendor(p)) { if (!innew) live(p); next }
            if ((p in owned) && !listed(conf, p)) { npkg++; next }          # comes back with its package
            if (!innew) { live(p); next }
            if (same_as_new(p)) next
            if (nt == "d" || !wins(p)) { hold(p, "i"); next }
            save(p); live(p); note("u", p)
            next
        }
        # a file of the image, changed by the user
        if (om[p] ~ /^d /) retyped[p] = 1
        if (p in pksame) next                                               # changed by the package manager
        if (vendor(p) || !wins(p)) { if (!innew || !same_as_new(p)) hold(p, "i"); next }
        if (!innew) { live(p); note("g", p); next }
        if (same_as_new(p)) next
        if (nt == "d") {
            # the user replaced a directory of the image by something else (a link elsewhere): theirs, as it was
            if (om[p] ~ /^d /) { print "R\t" p; live(p); note("u", p) } else hold(p, "i")
            next
        }
        if (new_is_old_image(p) || quiet(p)) { live(p); next }
        save(p); live(p); note("u", p)
    }
    END {
        if (pass != 3) exit
        # what the image had and the old system has not: deleted by the user (or by the system itself)
        if (!fb) for (p in om) if (!(p in seen)) gone[p] = 1
        for (p in gone) {
            d = parent(p)
            if ((d in gone) || (d in retyped) || !(p in ns) || never(p) || other(p) || vendor(p) || quiet(p)) continue
            if (p ~ /^etc\/uci-defaults\//) continue                        # they remove themselves when they ran
            if ((p in nown) && !(nown[p] in inst)) { back[nown[p]] = 1; continue }     # of a package that was removed
            if (!userarea(p)) continue
            # Deleted by the user: not one of the programs the system is made of, and not a file that went with an
            # upgrade of its package (the old system would still list it)
            if (enable_link(p) || (!project(p) && !aptsrc(p) && !script(p) && (!(p in nown) || (p in owned)))) {
                print "R\t" p; note("d", p)
            } else note("k", p)
        }
        # a package the user removed is part of the image and back: a service the old system did not have is not
        # enabled; one it had, from another package (dnsmasq-full for dnsmasq), is as the old system had it
        nback = 0
        for (a in back) { note("p", a); nback++ }
        if (nback) for (p in nown) if ((nown[p] in back) && service_file(p)) {
            b = p; sub(/.*\//, "", b)
            if (p in seen) svcold[b] = 1
            else svc[b] = 1
        }
        # without a manifest: a service the old system had and did not enable stays off
        if (fb) for (p in had) if (service_file(p)) { b = p; sub(/.*\//, "", b); known[b] = 1 }
        for (p in ns) {
            if (!enable_link(p)) continue
            b = service_of(p)
            if (nback && (b in svc)) print "R\t" p
            else if (nback && (b in svcold) && !(p in seen)) print "R\t" p
            else if (fb && !(p in had) && (b in known)) { print "R\t" p; note("e", p) }
        }
        # ... and a grant of sudo that the old system did not have is not taken from the new image
        if (fb) for (p in ns) if (p ~ /^etc\/sudoers\.d\/[^\/]*$/ && !(p in had) && f(ns[p], 1) != "d") { print "R\t" p; note("s", p) }
        print "n\t" nl + 0 "\tl"; print "n\t" nh + 0 "\th"; print "n\t" nsv + 0 "\ts"
        print "c\t" files + 0 "\t" npkg + 0
    }'
}
# carry_idmap OLD NEW: "u OLD NEW" and "g OLD NEW" for the accounts both systems have under another number (Ubuntu
# 24.04 and 26.04 number messagebus, sshd, bluetooth and others differently): what is carried follows the name
carry_idmap() {
    for _cf in passwd:u group:g; do
        [ -f "$1/etc/${_cf%:*}" ] && [ -f "$2/etc/${_cf%:*}" ] || continue
        awk -F: -v k="${_cf#*:}" 'NR == FNR { old[$1] = $3; next }
            ($1 in old) && old[$1] != $3 && old[$1] != "" && $3 != "" { print k, old[$1], $3 }' \
            "$1/etc/${_cf%:*}" "$2/etc/${_cf%:*}" || return 1
    done
}
# carry_accounts_plan OLD NEW, before the plan is made: who owns what in the new system. A file belongs to an account,
# not to a number: an owner the old system has a name for is carried by that name, under the number the name has in
# the new system - the new image's when it has the account (carry_idmap), else the old number when the new system
# does not use it, else a free one (a system account: the highest below 1000; a user: the lowest from 1000 on), all
# written to idmap for mu300-carry. merge_accounts brings the users from 1000 on and carry_accounts the system
# accounts added on the device, and carry_accounts then holds the result against this plan. A number the old system
# has NO name for stays the number - unless an account of the new system has it: such a file would become that
# account's, so it is set aside instead (carry_plan, with $CARRY_T/ids: "ou"/"og" the numbers the old system names,
# "nu"/"ng" the numbers taken in the new one). $CARRY_T/acct.group, acct.passwd: the lines of system accounts to add;
# acct.renum: "passwd|group NAME NUMBER" for the users merge_accounts brings.
carry_accounts_plan() {
    for _cf in acct.group acct.passwd acct.renum ids; do : > "$CARRY_T/$_cf" || return 1; done
    for _cf in group passwd; do [ -f "$1/etc/$_cf" ] && [ -f "$2/etc/$_cf" ] || return 0; done
    awk -F: -v T="$CARRY_T" '
        function free(used, sys,   i) {
            if (sys) { for (i = 999; i >= 100; i--) if (!(i in used)) return i; return "" }
            for (i = 1000; i < 60000; i++) if (!(i in used)) return i
            return ""
        }
        function line(   i, s) { s = $1; for (i = 2; i <= NF; i++) s = s ":" $i; return s }
        function one(k, file, names, used,   n, sys) {
            if ($3 == "") return
            print "o" k " " $3 >> (T "/ids")
            if ($1 in names) return
            n = $3; sys = ($3 < 1000 || $3 >= 60000)
            if (n in used) {
                n = free(used, sys)
                if (n == "") { print "r\ta\t" $1 " (" file " " $3 ")" >> (T "/plan.accounts"); return }
                print k " " $3 " " n >> (T "/idmap")
                if (k == "g") gmap[$3] = n
            }
            used[n] = 1
            if (!sys) { print file " " $1 " " n >> (T "/acct.renum"); return }
            $3 = n
            if (k == "u" && ($4 in gmap)) $4 = gmap[$4]
            print line() >> (T "/acct." file)
        }
        FILENAME == ARGV[1] { split($0, a, " "); if (a[1] == "g") gmap[a[2]] = a[3]; next }
        FILENAME == ARGV[2] { gname[$1] = 1; gid[$3] = 1; next }
        FILENAME == ARGV[3] { uname[$1] = 1; uid[$3] = 1; next }
        FILENAME == ARGV[4] { one("g", "group", gname, gid); next }
        { one("u", "passwd", uname, uid) }
        END { for (i in uid) print "nu " i >> (T "/ids"); for (i in gid) print "ng " i >> (T "/ids") }
    ' "$CARRY_T/idmap" "$2/etc/group" "$2/etc/passwd" "$1/etc/group" "$1/etc/passwd"
}
# carry_accounts OLD NEW, after merge_accounts: the accounts carry_accounts_plan chose, with their shadow entries, and
# the subordinate ids (subuid, subgid) of the accounts the new system did not have
carry_accounts() {
    for _cf in passwd:shadow group:gshadow; do
        _ca=${_cf%:*}; _cs=${_cf#*:}
        [ -s "$CARRY_T/acct.$_ca" ] || continue
        for _cx in "$_ca" "$_cs"; do
            [ -f "$1/etc/$_cx" ] && [ -f "$2/etc/$_cx" ] || continue
            # renamed into place, with the owner and mode of the file, as merge_accounts does
            cp -p "$2/etc/$_cx" "$2/etc/$_cx.mu300-new" && {
                cat "$2/etc/$_cx"
                if [ "$_cx" = "$_ca" ]; then cat "$CARRY_T/acct.$_ca"
                else awk -F: 'NR == FNR { add[$1] = 1; next } ($1 in add)' "$CARRY_T/acct.$_ca" "$1/etc/$_cx"; fi
            } > "$2/etc/$_cx.mu300-new" && mv -f "$2/etc/$_cx.mu300-new" "$2/etc/$_cx" || { rm -f "$2/etc/$_cx.mu300-new"; return 1; }
        done
    done
    # the users merge_accounts brought: the number the plan gave them, and their group under its number
    if [ -s "$CARRY_T/acct.renum" ]; then
        for _cx in passwd group; do
            [ -f "$2/etc/$_cx" ] || continue
            awk -F: -v OFS=: -v f="$_cx" 'FILENAME == ARGV[1] { split($0, a, " "); if (a[1] == "g") gmap[a[2]] = a[3]; next }
                FILENAME == ARGV[2] { split($0, a, " "); if (a[1] == f) num[a[2]] = a[3]; next }
                ($1 in num) { $3 = num[$1]; if (f == "passwd" && ($4 in gmap)) $4 = gmap[$4] }
                { print }' "$CARRY_T/idmap" "$CARRY_T/acct.renum" "$2/etc/$_cx" > "$CARRY_T/acct" || return 1
            cmp -s "$CARRY_T/acct" "$2/etc/$_cx" || {
                cp -p "$2/etc/$_cx" "$2/etc/$_cx.mu300-new" && cat "$CARRY_T/acct" > "$2/etc/$_cx.mu300-new" &&
                    mv -f "$2/etc/$_cx.mu300-new" "$2/etc/$_cx" || { rm -f "$2/etc/$_cx.mu300-new"; return 1; }
            }
        done
    fi
    # The files were carried by the plan: every account of the old system must now have the number the plan says,
    # and no number may have two names that were two accounts. Anything else is not put in place.
    for _cf in passwd:u group:g; do
        [ -f "$1/etc/${_cf%:*}" ] && [ -f "$2/etc/${_cf%:*}" ] || continue
        awk -F: -v k="${_cf#*:}" 'FILENAME == ARGV[1] { split($0, a, " "); if (a[1] == k) map[a[2]] = a[3]; next }
            FILENAME == ARGV[2] { if ($3 != "") now[$1] = $3; next }
            $3 != "" && ($1 in now) && now[$1] != (($3 in map) ? map[$3] : $3) { bad = 1; print "  " $1 ": " now[$1] " in the new system, the plan was " (($3 in map) ? map[$3] : $3) > "/dev/stderr" }
            END { exit bad }' "$CARRY_T/idmap" "$2/etc/${_cf%:*}" "$1/etc/${_cf%:*}" ||
            { echo "  the accounts of the new system are not the ones the files were carried for" >&2; return 1; }
    done
    for _cx in subuid subgid; do
        [ -f "$1/etc/$_cx" ] && [ -f "$2/etc/$_cx" ] || continue
        awk -F: 'NR == FNR { have[$1] = 1; next } !($1 in have)' "$2/etc/$_cx" "$1/etc/$_cx" > "$CARRY_T/acct" || return 1
        [ ! -s "$CARRY_T/acct" ] || cat "$CARRY_T/acct" >> "$2/etc/$_cx" || return 1
    done
    # An account of the image that the old system did not have - the user deleted it, or the release added it - must
    # not come with the image's well-known password (ubuntu/ubuntu) or with none: it is locked, and said.
    [ -f "$1/etc/passwd" ] && [ -f "$2/etc/shadow" ] || return 0
    awk -F: -v OFS=: -v T="$CARRY_T" 'NR == FNR { old[$1] = 1; next }
        !($1 in old) && $2 !~ /^[!*]/ { print "r\tl\t" $1 >> (T "/plan"); $2 = "!" $2 }
        { print }' "$1/etc/passwd" "$2/etc/shadow" > "$CARRY_T/acct" || return 1
    if ! cmp -s "$CARRY_T/acct" "$2/etc/shadow"; then
        cp -p "$2/etc/shadow" "$2/etc/shadow.mu300-new" && cat "$CARRY_T/acct" > "$2/etc/shadow.mu300-new" &&
            mv -f "$2/etc/shadow.mu300-new" "$2/etc/shadow" || { rm -f "$2/etc/shadow.mu300-new"; return 1; }
    fi
    return 0
}
# carry_report NEW OS FROM TO MODE: the plan's lines for people, on stdout and on top of NEW/etc/mu300/update-report
# (what earlier updates wrote stays below it: the file came along like every file of the user)
carry_report() {
    _cr=$1/$CARRY_REPORT
    {
        printf '==== %s: %s -> %s, %s ====\n' "$2" "$3" "$4" "$(date '+%Y-%m-%d %H:%M' 2>/dev/null)"
        awk -F'\t' -v kept="/$CARRY_KEPT/$3" -v fb="$CARRY_FALLBACK" -v mode="$5" -v nohold="$CARRY_NOHOLD" '
            function list(code, title, pre,   i) {
                if (!n[code]) return
                print title
                for (i = 1; i <= n[code]; i++) print "  " pre item[code, i]
            }
            $1 == "c" { files = $2; npkg = $3; next }
            $1 == "n" && $3 == "l" { mb = int($2 / 2048); next }
            $1 == "r" { p = $0; sub(/^r\t[^\t]*\t/, "", p); n[$2]++; item[$2, n[$2]] = p }
            END {
                printf "Everything you added to the system was carried over: %d files, %d MB%s.\n", files, mb,
                    mode == "link" ? " (the previous system is not kept)" : ""
                if (fb) {
                    print "The image this system came from has no list of its files here, so a file you changed could not be"
                    print "told from one the old release shipped: where the new release has another file, the new one is in use,"
                    print "and a file of the image that you had deleted is back."
                }
                list("u", "Yours is in use where the new release has another version (the one of the release: " kept "/image):", "/")
                list("g", "Yours is in use; the new release no longer has this file:", "/")
                list("i", "The version of the release is in use; yours is in " kept "/user:", "/")
                if (nohold == "") list("f", "Differed from the new release and were replaced; as they were: " kept "/user:", "/")
                else list("f", "Differed from the new release and were replaced. There was no room to set them aside: they are in the previous system until mu300-update clean, or the next update:", "/")
                list("x", "The release has a file or a link where this directory was; what you had in it: " kept "/user:", "/")
                list("d", "Deleted again, as you had deleted them:", "/")
                list("k", "Back, though you had deleted them (the system needs them, or it cannot be told):", "/")
                list("p", "Packages you had removed are part of the image, and back (their services are as the previous system had them):", "")
                list("e", "Left off, as in the previous system (the new release enables them):", "/")
                list("s", "Not taken from the new release, as the previous system did not have them (rules of sudo):", "/")
                list("l", "Accounts of the release that the previous system did not have are locked (passwd NAME sets a password):", "")
                list("m", "The owner or mode you gave these is the one of the release again:", "/")
                list("o", "Owned by a number that no account had in the previous system and an account of the new one has: not put in place, but in " kept "/user:", "/")
                list("q", "Set-user-id and set-group-id bits and capabilities were taken off: the owner has another number in the new system:", "/")
                list("a", "Accounts that could not be carried over (the files they own keep the number):", "")
                if (n["v"]) print "Files that were there when the update looked and gone when it came to carry them (the running system removed them): " item["v", 1]
                if (npkg) printf "%d files of packages are not carried: they come with their packages.\n", npkg
            }' "$CARRY_T/plan"
        echo "Packages installed on the device:"
        cat "$CARRY_T/upk"
        echo
    } > "$CARRY_T/report" || return 1
    cat "$CARRY_T/report"
    if [ -f "$_cr" ] && [ ! -L "$_cr" ]; then cat "$_cr" >> "$CARRY_T/report" || return 1; fi
    # root's alone from the moment it is there: it names the user's files, also those under /root and /home
    rm -f "$_cr" 2>/dev/null; [ ! -e "$_cr" ] && [ ! -L "$_cr" ] || return 1
    mkdir -p "$1/etc/mu300" && ( umask 077; cat "$CARRY_T/report" > "$_cr" ) && chmod 600 "$_cr" || return 1
    [ "$(id -u)" != 0 ] || chown 0:0 "$_cr" || return 1
    # the note at the next login, until "mu300-update report" has shown it (notice, and OpenWrt's profile.d)
    if grep -q "^r$CARRY_TAB" "$CARRY_T/plan" || [ -n "$CARRY_FALLBACK" ]; then : > "$_cr.new"; else rm -f "$_cr.new"; fi
}
# The feeds of the OpenWrt release (#420): distfeeds.list names the release and the kmods directory of its kernel. One
# the user changed (another mirror, most often) wins like any setting, and kept the release it was written for: the
# feeds of 25.12.5 on an image of 25.12.6, whose kmods are another kernel's, and every package that needs a kmod
# "breaks" the kernel. The user's lines follow the release of the new image: in each line of an OpenWrt release feed
# its version and kmods directory; the host, the scheme and any line of their own stay theirs.
# apk_feeds_of NEW: "VERSION KMODS" of the image's distfeeds.list (KMODS - when it has none), before the carry
apk_feeds_of() {
    _af=$1/etc/apk/repositories.d/distfeeds.list
    [ -f "$_af" ] && [ ! -L "$_af" ] || return 0
    _av=$(sed -n 's|.*/releases/\([0-9][0-9A-Za-z.-]*\)/targets/.*|\1|p' "$_af" | head -n 1)
    _ak=$(sed -n 's|.*/releases/[^/]*/targets/.*/kmods/\([0-9A-Za-z._-]*\)/.*|\1|p' "$_af" | head -n 1)
    [ -z "$_av" ] || echo "$_av ${_ak:--}"
}
# apk_feeds_follow NEW VERSION KMODS: the distfeeds.list in NEW (the user's, after the carry) on that release
apk_feeds_follow() {
    _af=$1/etc/apk/repositories.d/distfeeds.list
    [ -f "$_af" ] && [ ! -L "$_af" ] && [ -n "$2" ] || return 0
    # (a release feed of OpenWrt: /releases/X.Y.Z[-rcN]/ and then targets/T/S/ or packages/ARCH/)
    _ar='/releases/[0-9]+\.[0-9]+\.[0-9]+(-rc[0-9]+)?/(targets/[^/]+/[^/]+/|packages/[^/]+/)'
    _ae="\\#$_ar#s#/releases/[^/]+/#/releases/$2/#"
    [ "${3:--}" = - ] || _ae="$_ae;\\#$_ar#s#/kmods/[^/]+/#/kmods/$3/#"
    # (a copy first: the file itself may be a second name of the old system's, which is never written to)
    cp -p "$_af" "$_af.mu300" && sed -E -e "$_ae" "$_af" > "$_af.mu300" || { rm -f "$_af.mu300"; return 0; }
    if [ "$(cat "$_af")" = "$(cat "$_af.mu300")" ]; then rm -f "$_af.mu300"; return 0; fi
    mv -f "$_af.mu300" "$_af" && echo "  /etc/apk/repositories.d/distfeeds.list (yours): its OpenWrt feeds follow the new release, $2"
}
# carry_system OLD NEW OS MODE: all of it, between the unpacking of NEW and the switch: the files, the accounts, the
# packages to install again (upk_record). Status 3: not enough room, and nothing but NEW was touched.
carry_system() {
    _co=$1 _cn=$2 _cos=$3 _cmode=${4:-copy}
    case $_cmode in copy|link) ;; *) return 1 ;; esac
    [ -d "$_co" ] && [ -d "$_cn" ] || return 1
    CARRY_KIND=$(os_kind "$_cos") || return 1
    _cfeeds=; [ "$CARRY_KIND" != openwrt ] || _cfeeds=$(apk_feeds_of "$_cn")
    CARRY_BIN=${MU300_CARRY:-$_cn/opt/mu300/bin/mu300-carry}
    CARRY_T=$_cn/.mu300-carry
    _cfrom=$(cat "$_co/etc/mu300/image-version" 2>/dev/null) || _cfrom=
    case $_cfrom in ''|*[!0-9A-Za-z._-]*) _cfrom=unknown ;; esac
    _cto=$(cat "$_cn/etc/mu300/image-version" 2>/dev/null) || _cto=unknown
    image_own_save "$_cn" || return 1
    # the working directory is root's alone: it holds the lists of the user's files, and the manifest that is used
    rm -rf "$CARRY_T"; ( umask 077; mkdir "$CARRY_T" ) && chmod 700 "$CARRY_T" || return 1
    for _cf in manifest pkg sum.old sum.new pksame; do : > "$CARRY_T/$_cf" || return 1; done
    tr -s ' \n' '\n\n' < "$_cn/opt/mu300/lib/path-commands" > "$CARRY_T/cmds" 2>/dev/null || : > "$CARRY_T/cmds"
    CARRY_FALLBACK=; CARRY_KEEP=; CARRY_NOHOLD=
    if ! carry_manifest "$_co" "$_cn" "$_cos" "$_cfrom" "$CARRY_T/manifest" || [ ! -s "$CARRY_T/manifest" ]; then
        CARRY_FALLBACK=1
        CARRY_KEEP=$(keep_list "$_cos" | tr ' ' '|')
        : > "$CARRY_T/manifest"
        echo "  no list of the files of $_cfrom here: carrying what the new image does not have, and the places an update always kept"
    fi
    { carry_pkgdb "$_co" "$CARRY_KIND" O C S && carry_pkgdb "$_cn" "$CARRY_KIND" N D "" &&
        upk_installed "$_co" "$CARRY_KIND" | sed "s/^/I$CARRY_TAB/"; } > "$CARRY_T/pkg" || return 1
    "$CARRY_BIN" scan "$_cn" > "$CARRY_T/scan.new" && "$CARRY_BIN" scan "$_co" > "$CARRY_T/scan.old" || return 1
    for _cp in 1 2; do
        carry_plan "$_cp" < "$CARRY_T/scan.old" > "$CARRY_T/ask" || return 1
        sed -n "s/^O$CARRY_TAB//p" "$CARRY_T/ask" | "$CARRY_BIN" sum "$_co" >> "$CARRY_T/sum.old" || return 1
        sed -n "s/^N$CARRY_TAB//p" "$CARRY_T/ask" | "$CARRY_BIN" sum "$_cn" >> "$CARRY_T/sum.new" || return 1
        sed -n "s/^K$CARRY_TAB//p" "$CARRY_T/ask" | carry_pksame "$_co" >> "$CARRY_T/pksame" || return 1
    done
    # who owns what in the new system is settled before the plan and before a file is carried
    carry_idmap "$_co" "$_cn" > "$CARRY_T/idmap" && carry_accounts_plan "$_co" "$_cn" || return 1
    carry_plan 3 < "$CARRY_T/scan.old" > "$CARRY_T/plan" || return 1
    [ ! -s "$CARRY_T/plan.accounts" ] || cat "$CARRY_T/plan.accounts" >> "$CARRY_T/plan"
    # room: what is copied (by link a file costs nothing), what is set aside, and a margin (5 % and 32 MB; by link,
    # where only directories, links and the report are written, 8 MB)
    _cneed=$(awk -F'\t' -v m="$_cmode" '$1 == "n" && !(m == "link" && $3 != "s") { n += $2 }
        END { printf "%d\n", n / 2 + n / 40 + (m == "link" ? 8192 : 32768) }' "$CARRY_T/plan")
    _cfree=$(df -Pk "$_cn" | awk 'NR == 2 { print $4 }')
    if [ "${_cfree:-0}" -lt "$_cneed" ] && [ -n "$CARRY_FALLBACK" ]; then
        # without a manifest most of what would be set aside is the old image's own: the update goes on without it
        _cneed=$(awk -F'\t' -v m="$_cmode" '$1 == "n" && $3 != "h" && !(m == "link" && $3 != "s") { n += $2 }
            END { printf "%d\n", n / 2 + n / 40 + (m == "link" ? 8192 : 32768) }' "$CARRY_T/plan")
        CARRY_NOHOLD=1
    fi
    if [ "${_cfree:-0}" -lt "$_cneed" ]; then
        echo "  not enough room to carry your files over beside the previous system: $((_cneed / 1024)) MB needed, $((${_cfree:-0} / 1024)) MB free" >&2
        rm -rf "$_cn/.mu300-image" "$CARRY_T"
        return 3
    fi
    # the release's versions aside first, then what is in the way goes, then the user's files come
    _ck=$_cn/$CARRY_KEPT/$_cfrom
    # (it holds copies of the user's files, some of them not everyone's to read: root's alone, whatever it was when
    # it came along from an earlier update; each file in it keeps its own owner and mode)
    if grep -q "^[SH]$CARRY_TAB" "$CARRY_T/plan" || [ -e "$_cn/$CARRY_KEPT" ] || [ -L "$_cn/$CARRY_KEPT" ]; then
        [ ! -L "$_cn/$CARRY_KEPT" ] || rm -f "$_cn/$CARRY_KEPT"
        ( umask 077; mkdir -p "$_cn/$CARRY_KEPT" ) && chmod 700 "$_cn/$CARRY_KEPT" || return 1
        [ "$(id -u)" != 0 ] || chown 0:0 "$_cn/$CARRY_KEPT" || return 1
        ( umask 077; mkdir -p "$_ck/image" "$_ck/user" ) || return 1
    fi
    sed -n "s/^S$CARRY_TAB//p" "$CARRY_T/plan" > "$CARRY_T/list"
    [ ! -s "$CARRY_T/list" ] || "$CARRY_BIN" copy "$_cn" "$_ck/image" < "$CARRY_T/list" >/dev/null || return 1
    sed -n "s/^R$CARRY_TAB//p" "$CARRY_T/plan" | while IFS= read -r _cl; do
        _cp=$(carry_unesc "$_cl")
        case /$_cp/ in *//*|*/../*|*/./*) echo "  a path that cannot be: $_cl" >&2; exit 1 ;; esac
        rm -rf "$_cn/$_cp" || exit 1
    done || return 1
    sed -n "s/^L$CARRY_TAB//p" "$CARRY_T/plan" > "$CARRY_T/list"
    : > "$CARRY_T/done"
    [ ! -s "$CARRY_T/list" ] || "$CARRY_BIN" "$_cmode" "$_co" "$_cn" "$CARRY_T/idmap" < "$CARRY_T/list" > "$CARRY_T/done" || return 1
    # (the device's files: by link whatever the mode, see live in carry_plan)
    sed -n "s/^V$CARRY_TAB//p" "$CARRY_T/plan" > "$CARRY_T/list"
    [ ! -s "$CARRY_T/list" ] || "$CARRY_BIN" link "$_co" "$_cn" "$CARRY_T/idmap" < "$CARRY_T/list" > "$CARRY_T/done.v" || return 1
    [ ! -s "$CARRY_T/done.v" ] || grep '^! ' "$CARRY_T/done.v" >> "$CARRY_T/done" || :
    # (a running system removes files of its own while the update looks: they are counted, and said)
    # (set-id bits and capabilities do not go with a file to another number: mu300-carry took them off, and says)
    sed -n "s/^! /r${CARRY_TAB}q${CARRY_TAB}/p" "$CARRY_T/done" >> "$CARRY_T/plan"
    _cgone=$(sed -n 's/.* \([0-9][0-9]*\) gone meanwhile$/\1/p' "$CARRY_T/done")
    [ "${_cgone:-0}" = 0 ] || printf 'r\tv\t%s\n' "$_cgone" >> "$CARRY_T/plan"
    sed -n "s/^H$CARRY_TAB//p" "$CARRY_T/plan" > "$CARRY_T/list"
    if [ -s "$CARRY_T/list" ] && [ -z "$CARRY_NOHOLD" ]; then
        "$CARRY_BIN" "$_cmode" "$_co" "$_ck/user" "$CARRY_T/idmap" < "$CARRY_T/list" >/dev/null || return 1
    fi
    # (again, now that what came along from the old system is in it, with the mode it had there)
    if [ -d "$_cn/$CARRY_KEPT" ] && [ ! -L "$_cn/$CARRY_KEPT" ]; then
        chmod 700 "$_cn/$CARRY_KEPT" || return 1
        [ "$(id -u)" != 0 ] || chown 0:0 "$_cn/$CARRY_KEPT" || return 1
    fi
    sed -n "s/^M$CARRY_TAB//p" "$CARRY_T/plan" | while IFS= read -r _cl; do
        _cp=$_cn/$(carry_unesc "${_cl#*"$CARRY_TAB"}"); _cl=${_cl%%"$CARRY_TAB"*}
        # shellcheck disable=SC2086
        set -- $_cl
        [ -L "$_cp" ] || { chown "$2:$3" "$_cp" && chmod "$1" "$_cp"; } || exit 1
    done || return 1
    if [ "$CARRY_KIND" = openwrt ]; then
        stale_config_clean "$_cn"
        # shellcheck disable=SC2086
        [ -z "$_cfeeds" ] || apk_feeds_follow "$_cn" $_cfeeds
    fi
    merge_accounts "$_co" "$_cn" && carry_accounts "$_co" "$_cn" || { echo "  could not carry the accounts over" >&2; return 1; }
    image_own_restore "$_cn" || return 1
    # the packages installed on the device: written down, their settings set aside, put back at the first boot
    upk_record "$_co" "$_cn" "$_cos" > "$CARRY_T/upk" || { cat "$CARRY_T/upk"; echo "  could not write down the packages installed on the device" >&2; return 1; }
    rm -rf "$_cn/.mu300-image"
    # an apt source added on the device is upk_apt_keep's to keep (in use, or off for another Ubuntu release): where
    # it is in use, everything of the file comes along (its owner and times), as for what was carried
    sed -n "s/^A$CARRY_TAB//p" "$CARRY_T/plan" | while IFS= read -r _cl; do
        [ ! -f "$_cn/$(carry_unesc "$_cl")" ] || printf '%s\n' "$_cl"
    done > "$CARRY_T/list"
    [ ! -s "$CARRY_T/list" ] || "$CARRY_BIN" "$_cmode" "$_co" "$_cn" "$CARRY_T/idmap" < "$CARRY_T/list" >/dev/null || return 1
    carry_report "$_cn" "$_cos" "$_cfrom" "$_cto" "$_cmode" || return 1
    rm -rf "$CARRY_T"
    : > "$_cn/.mu300-carried"       # all of it was done (carry_run looks, and removes it)
}
# report: what the last updates wrote, and the note at login goes
report() {
    _cr=${MU300_SYSROOT:-}/$CARRY_REPORT
    [ -s "$_cr" ] || { echo "no update has left a report here"; return 0; }
    cat "$_cr"
    rm -f "$_cr.new" "$MOTD_DIR/61-mu300-update-report" 2>/dev/null
    return 0
}
# carry_need OS...: KiB the carry block will write for these systems beside the previous ones, for apply's rule of
# free space (space_needed): what each holds that its image did not bring - its size less its image's files as its
# manifest has them (in 4 KiB blocks, as the filesystem keeps them) - with the carry's margin (5 %, 32 MB). Nothing
# for a system whose image's manifest is not here before the new image is (a release before the manifests: the carry
# block counts it exactly once the new image is unpacked, and stops before anything is changed), for --no-rollback
# (CARRY_MODE link: nothing is copied) and for MU300_UPDATE_KEEP=list. An estimate before the download; carry_system
# has the exact figure, and the last word.
carry_need() {
    _nt=0
    if [ "${CARRY_MODE:-copy}" = copy ] && [ "${MU300_UPDATE_KEEP:-all}" != list ]; then
        for _no in "$@"; do
            _nd=$DISK/$_no
            [ -d "$_nd" ] && [ ! -L "$_nd" ] || continue
            _nw=$(mktemp -d 2>/dev/null) || continue
            if carry_manifest "$_nd" "$_nd" "$_no" "$(cat "$_nd$VERSION_FILE" 2>/dev/null)" "$_nw/m"; then
                # (the device's own files are second names, never a copy: neither they nor the image's files there
                # count, see live in carry_plan)
                _nv=$(vendor_list "$_no" | tr ' ' '|')
                _ni=$(awk -v v="^(${_nv:-/})/" '{ p = $0; for (i = 0; i < 6; i++) p = substr(p, index(p, " ") + 1) }
                    p ~ v { next } $1 == "f" { k += int(($5 + 4095) / 4096) * 4; next } { k += 4 } END { printf "%d\n", k }' "$_nw/m")
                # (one filesystem: what is mounted in a system is not carried; nor what the carry block leaves out)
                _nz=$( { du -skx "$_nd" 2>/dev/null || du -sk "$_nd"; } | awk 'NR == 1 { print $1 + 0 }')
                _nx=0
                for _nn in proc sys dev run tmp var/tmp var/cache $(vendor_list "$_no"); do
                    [ -d "$_nd/$_nn" ] && [ ! -L "$_nd/$_nn" ] || continue
                    _nx=$((_nx + $( { du -skx "$_nd/$_nn" 2>/dev/null || du -sk "$_nd/$_nn"; } | awk 'NR == 1 { print $1 + 0 }') ))
                done
                _nu=$(( ${_nz:-0} - _nx - ${_ni:-0} ))
                [ "$_nu" -gt 0 ] || _nu=0
                _nt=$((_nt + _nu + _nu / 20 + 32768))
            fi
            rm -rf "$_nw"
        done
    fi
    echo "$_nt"
}
# --- carry end

# --- delta begin
# An update writes only what changed (docs/FINDINGS.md 131). Unpacking the whole new image beside the running system
# needed room for a second copy of it: an OpenWrt with Docker in it (472 of 775 MiB) could not be updated in an
# 804 MiB region at all. Now a file of the new image that the installed system has byte for byte - same type, mode,
# owner, size and content, no extended attribute but Android's SELinux label - is not written again: it becomes a
# second name (a hard link) of the installed one. Only what changed takes room. The new image's manifest
# (etc/mu300/image-manifest.gz, published as mu300-*-rootfs.manifest.gz) says what its files are; mu300-carry same
# hashes the installed ones; the room needed is counted from that before anything is written; mu300-carry tarfilter
# leaves the linked files out of the tar stream on its way to tar - comparing each with the installed file byte for
# byte as it passes, so a file that changed after it was looked at is written after all - and mu300-carry tarlink
# makes the links once tar is done.
#
# Two names of one file are one file: what is done to the file through one name - written into, truncated, given
# another mode or owner - is done to the other system's too. Package managers never do that (dpkg and apk unpack
# beside the file and rename it over), but an editor does (nano and busybox vi write into the file; vim does for a
# file with two names), and so do "cp FILE EXISTING", ">>" and chmod. So what is linked is limited to what nothing
# edits (delta_candidates):
#   * the trees of programs and libraries: usr (but usr/local), bin, sbin, lib*, opt/mu300 - never etc, var, root,
#     home, srv, www, usr/local, opt/<other>: what the user and the system change. Not lib/apk and usr/lib/opkg
#     (package databases) and not usr/lib/locale/locale-archive (localedef adds to it in place);
#   * binaries only: a file with a NUL byte in it. Text - scripts, units, Python and Perl modules, the project's own
#     scripts, anything an editor opens - is written as before (on Ubuntu 24.04 74 of its 302 MiB of such files).
# What the update itself does to the new system after the unpack never writes into such a file: the carry block
# makes or replaces whole files (mu300-carry unlinks what is in the way), the accounts and the report are renamed
# into place, and modules go into lib/modules as new files (kernel_modules_into_systems removes before it links).
# The previous system kept for rollback (<os>.old) is then as whole as before; rollback, clean and the swap only
# rename and unlink. A system that changes such a file in place afterwards changes both (a user's cp over a program
# of the image, a chmod of one): the report of the update says how many files the two share.
#
# A release without manifests, or an image without mu300-carry tarfilter: the whole image is unpacked, as before.
# MU300_DELTA=0 asks for that too.
DELTA_TOOLS="opt/mu300/bin/mu300-carry opt/mu300/bin/mu300-update usr/bin/busybox opt/mu300/bin/busybox etc/mu300/image-manifest.gz etc/mu300/image-version"
# delta_tools TARBALL WORK: those parts of the new image out of its tarball into WORK/root (root's alone): a pass over
# the image that writes a few MB. Status 1 when the image has not even mu300-carry. (tools/android-install.sh does the
# same with Android's tar.)
delta_tools() {
    rm -rf "$2" && ( umask 077; mkdir -p "$2/root" ) || return 1
    _dm=; for _dx in $DELTA_TOOLS; do _dm="$_dm ./$_dx"; done
    # (a member the image does not have - Ubuntu has no opt/mu300/bin/busybox - makes tar fail at the end: what it
    # found is there all the same)
    # shellcheck disable=SC2086
    tar -xzf "$1" -C "$2/root" $_dm 2>/dev/null
    # shellcheck disable=SC2086
    [ -f "$2/root/opt/mu300/bin/mu300-carry" ] || busybox tar -xzf "$1" -C "$2/root" $_dm 2>/dev/null
    [ -f "$2/root/opt/mu300/bin/mu300-carry" ]
}
# delta_candidates < MANIFEST-LINES: the lines of files that may be linked (the trees above)
delta_candidates() {
    awk '$1 != "f" { next }
        { p = $0; for (i = 0; i < 6; i++) p = substr(p, index(p, " ") + 1) }
        p !~ /^(usr|bin|sbin|lib|lib32|lib64|libx32)\// && p !~ /^opt\/mu300\// { next }
        p ~ /^usr\/local\// || p ~ /^lib\/apk\// || p ~ /^usr\/lib\/opkg\// || p == "usr/lib/locale/locale-archive" { next }
        { print }'
}
# delta_kb < MANIFEST-LINES with LINK (the paths that are linked) as the first file: the KiB that unpacking the
# image writes - each file not linked in 4 KiB blocks, a block for each directory and for each link whose target does
# not fit into its inode (ext4: 60 bytes)
delta_kb() {
    awk 'FILENAME == ARGV[1] { l[$0] = 1; next }
        { p = $0; for (i = 0; i < 6; i++) p = substr(p, index(p, " ") + 1) }
        $1 == "f" && !(p in l) { k += int(($5 + 4095) / 4096) * 4; next }
        $1 == "f" { s += int(($5 + 4095) / 4096) * 4; next }
        $1 == "d" || ($1 == "l" && $5 > 59) { k += 4 }
        END { printf "%d %d\n", k, s }' "$@"
}
# delta_margin KB: what an unpack of KB wants free (the directories' own blocks, the journal: 2 % and 16 MB)
delta_margin() { echo $(($1 + $1 / 50 + 16384)); }
# delta_manifest MANIFEST.gz TAG OS OUT: its lines without the first into OUT, when it is the manifest of OS's image
# of release TAG and every line is one; else status 1
delta_manifest() {
    case $2 in ''|unknown|*[!0-9A-Za-z._-]*) return 1 ;; esac
    case $3 in ubuntu) _dk='ubuntu-[0-9][0-9].[0-9][0-9]' ;; openwrt|openwrt-luci) _dk=$3 ;; *) return 1 ;; esac
    [ -f "$1" ] && [ ! -L "$1" ] && gzip -t < "$1" 2>/dev/null || return 1
    _dl=$(gzip -dc < "$1" | head -n 1)
    # shellcheck disable=SC2254
    case $_dl in "mu300-image-manifest 1 "$_dk" $2") ;; *) return 1 ;; esac
    gzip -dc < "$1" | sed 1d > "$4" && carry_manifest_ok "$4" || { rm -f "$4"; return 1; }
}
# delta_plan OLD MANIFEST-LINES WORK HELPER: WORK/link, the files to link, and "KB LINKED_KB" on stdout - what the
# unpack writes, and what it does not write. HELPER: an mu300-carry that has "same".
delta_plan() {
    delta_candidates < "$2" | "$4" same "$1" > "$3/same" || return 1
    sed -n 's/^B //p' "$3/same" > "$3/link" || return 1
    delta_kb "$3/link" "$2"
}
# delta_estimate OLD MANIFEST-LINES WORK: the same figure before anything is downloaded, with the mu300-carry of the
# running system: exact where it has "same"; with only "sum" (the releases before this) every file it has byte for
# byte counts as linked, text too (what the new image's own helper decides after the download is the last word); no
# helper at all: the whole image
delta_estimate() {
    _dh=${MU300_BIN:-/opt/mu300/bin}/mu300-carry
    if [ -x "$_dh" ] && "$_dh" features 2>/dev/null | grep -qw same; then
        delta_plan "$1" "$2" "$3" "$_dh"
        return
    fi
    if [ -x "$_dh" ] && "$_dh" sum "$1" < /dev/null >/dev/null 2>&1; then
        delta_candidates < "$2" > "$3/cand" &&
            awk '{ p = $0; for (i = 0; i < 6; i++) p = substr(p, index(p, " ") + 1); print p }' "$3/cand" |
            "$_dh" sum "$1" > "$3/sum" || return 1
        awk 'FILENAME == ARGV[1] { p = $0; for (i = 0; i < 6; i++) p = substr(p, index(p, " ") + 1); h[p] = $6; next }
            { p = substr($0, index($0, " ") + 1); if ((p in h) && h[p] == $1) print p }' "$3/cand" "$3/sum" > "$3/link" || return 1
    else
        : > "$3/link"
    fi
    delta_kb "$3/link" "$2"
}
# delta_ready WORK OS: the parts delta_tools took out of the new image are all there and run here; WORK/lines is then
# its manifest (without the first line)
delta_ready() {
    _dbb=
    for _dx in usr/bin/busybox opt/mu300/bin/busybox; do
        [ -n "$_dbb" ] || { [ -f "$1/root/$_dx" ] && [ ! -L "$1/root/$_dx" ] && _dbb=$1/root/$_dx; }
    done
    [ -n "$_dbb" ] && "$_dbb" true 2>/dev/null || return 1
    _dc=$1/root/opt/mu300/bin/mu300-carry
    [ -f "$_dc" ] && [ ! -L "$_dc" ] && "$_dc" features 2>/dev/null | grep -qw tarfilter || return 1
    grep -q '^# --- delta begin' "$1/root/opt/mu300/bin/mu300-update" 2>/dev/null || return 1
    delta_manifest "$1/root/etc/mu300/image-manifest.gz" "$(head -n 1 "$1/root/etc/mu300/image-version" 2>/dev/null)" "$2" "$1/lines" || return 1
    ln -sf "$_dbb" "$1/busybox" && ln -sf "$_dc" "$1/carry"
}
# delta_clean DIR: what an update that was cut off left on the Linux partition DIR - a new system half unpacked
# (<os>.new, a whole system's worth of room: 98 % of F50-C's region), the work directories of this block, the
# installers' log - so that the room it took is free before the room is counted. Never a running system's.
delta_clean() {
    for _dx in $SYSTEMS; do
        for _dd in "$1/$_dx.new" "$1/.mu300-delta-$_dx" "$1/$_dx.new.carry-log"; do
            [ -e "$_dd" ] || [ -L "$_dd" ] || continue
            [ ! -d "$_dd" ] || ! [ / -ef "$_dd" ] || continue
            rm -rf "$_dd" && printf '%s: removed %s, left by an update that did not finish\n' "$_dx" "${_dd##*/}"
        done
    done
    return 0
}
# update_need TAG OS...: the KiB apply wants free before it downloads anything (one rule with space_needed's place in
# apply): for each system the download of its image, what unpacking it writes (the new image's manifest, the
# release's mu300-*-rootfs.manifest.gz or, from a file, the image's own, against the installed system:
# delta_estimate) and the copy of the user's files for the rollback (carry_need); then the kernel, the extras and
# the VPN module. The images' downloads are gone when the kernel step comes (apply_one removes each once unpacked):
# the kernel counts with its download beside them, or with its own step (kernel_need_kb), whichever is more.
# Status 1 when a manifest cannot be had (a release before them): space_needed's rule then.
update_need() {
    _ut=$1; shift
    stage_private || return 1
    _uw=$STAGE/.need
    rm -rf "$_uw"; ( umask 077; mkdir -p "$_uw" ) || return 1
    _un=0 _ud=0
    for _uo in "$@"; do
        _ua=$(rootfs_asset "$_uo"); _um=${_ua%.tar.gz}.manifest.gz
        if ! { fetch_verified "$_ut" "$_um" >/dev/null 2>&1 && cat "$STAGE/$_um" > "$_uw/m.gz"; }; then
            # from a file (a Magisk zip has no manifest of its own): the one in the image, read without unpacking it
            [ -n "${MU300_FROM:-}" ] && from_verified "$_ut" "$_ua" >/dev/null 2>&1 &&
                untar -xzOf "$STAGE/$_ua" ./etc/mu300/image-manifest.gz > "$_uw/m.gz" 2>/dev/null ||
                { rm -rf "$_uw"; return 1; }
        fi
        rm -f "$STAGE/$_um"
        delta_manifest "$_uw/m.gz" "$_ut" "$_uo" "$_uw/lines" || { rm -rf "$_uw"; return 1; }
        if [ "${MU300_DELTA:-1}" != 0 ]; then _ue=$(delta_estimate "$DISK/$_uo" "$_uw/lines" "$_uw") || { rm -rf "$_uw"; return 1; }
        else : > "$_uw/link"; _ue=$(delta_kb "$_uw/link" "$_uw/lines"); fi
        _uk=${_ue% *}
        # the image's download: its size where the release lists it, else half the image
        _us=$(asset_kb "$_ut" "$_ua") || _us=$(( (_uk + ${_ue#* }) / 2 ))
        _un=$(( _un + $(delta_margin "$_uk") + $(carry_need "$_uo") )) _ud=$((_ud + _us))
    done
    rm -rf "$_uw"
    # the kernel (bundles are 20 to 55 MB), the installed extras that follow the release, the VPN module (its
    # engines are 15 to 25 MB each), and 16 MB for what is not counted
    _ud=$(( _ud + $(asset_kb "$_ut" "$(kernel_asset)" || echo 65536) )); _uk=$(kernel_need_kb "$_ut")
    _un=$(( _un + 16384 + (_uk > _ud ? _uk : _ud) ))
    for _ux in $(extras_to_fetch "$_ut"); do _un=$((_un + $(asset_kb "$_ut" "$(extra_asset "$_ux")" || echo 16384) )); done
    [ ! -d "$EXTRA/vpn" ] || _un=$((_un + 65536))
    echo "$_un"
}
# asset_kb TAG NAME: the KiB the download of a release file takes: nothing when it is in the staging directory
# already; from a file or a directory (apply --from) what it holds; else as GitHub's list of the release's files says
# it (asked once, never again when it did not answer), else as the server answers a HEAD request (a mirror)
asset_kb() {
    [ ! -s "$STAGE/$2" ] || { echo 0; return 0; }
    if [ -n "${MU300_FROM:-}" ]; then
        _as=$(from_member "$2" 2>/dev/null | wc -c | tr -d ' ')
    else
        if [ -z "${ASSET_JSON+x}" ]; then
            _aa=${MU300_API_URL:-https://api.github.com/repos/$REPO}/releases/tags/$1
            if have curl; then ASSET_JSON=$(curl -fsSL --connect-timeout 15 --max-time 30 "$_aa" 2>/dev/null) || ASSET_JSON=
            else ASSET_JSON=$(wget -T 30 -qO- "$_aa" 2>/dev/null) || ASSET_JSON=; fi
        fi
        _as=$(printf '%s\n' "$ASSET_JSON" | awk -v f="$2" '
            function val(s) { sub(/^[^:]*:[ \t]*/, "", s); sub(/[ \t]*,?[ \t\r]*$/, "", s); gsub(/^"|"$/, "", s); return s }
            { gsub(/,"/, ",\n\""); gsub(/\{"/, "{\n\""); n = split($0, L, "\n")
              for (i = 1; i <= n; i++) {
                  if (L[i] ~ /^[ \t]*"name":/) an = val(L[i])
                  else if (L[i] ~ /^[ \t]*"size":/ && an == f) { print val(L[i]); exit }
              } }')
        if [ -z "$_as" ]; then
            _au=${MU300_RELEASE_URL:-${MU300_DOWNLOAD_URL:-https://github.com/$REPO/releases/download}/$1}/$2
            # (OpenWrt's wget, uclient-fetch, does not print the headers: the image's busybox does)
            _ab=${MU300_BIN:-/opt/mu300/bin}/busybox
            if have curl; then _as=$(curl -fsIL --connect-timeout 30 --max-time 60 "$_au" 2>/dev/null)
            elif [ -x "$_ab" ]; then _as=$("$_ab" wget -S --spider -T 60 "$_au" 2>&1)
            else _as=$(wget -S --spider -T 60 "$_au" 2>&1); fi
            _as=$(printf '%s\n' "$_as" | tr -d '\r' | awk 'tolower($1) == "content-length:" { n = $2 } END { print n }')
        fi
    fi
    case $_as in ''|0|*[!0-9]*) return 1 ;; esac
    echo $((_as / 1024 + 1))
}
# unpack_abort: an apply that ends before its switch - an error, ^C, a kill - leaves no half-made system behind
# (UNPACKING, set by apply_one: the new system and the work directory)
UNPACKING=
unpack_abort() {
    for _ua in $UNPACKING $DIFF_NEW; do
        case $_ua in "$DISK"/*.new|"$DISK"/.mu300-delta-*) rm -rf "$_ua" ;; esac
    done
    UNPACKING= DIFF_NEW=
    boot_abort
}
# delta_unpack TARBALL OLD NEW WORK: the image into NEW (made here), the files WORK/link names as second names of
# OLD's. tar is the system's (GNU tar on Ubuntu), else the image's busybox: GNU tar of 26.04 cannot unpack on 5.4
# (untar). The unpack must reach the end of the archive, which tarfilter writes into its log.
delta_unpack() {
    for _dx in tar bb; do
        rm -rf "$3" && mkdir -p "$3" || return 1
        rm -f "$4/log"
        if [ "$_dx" = tar ]; then
            "$4/busybox" gzip -dc < "$1" | "$4/carry" tarfilter "$2" "$4/link" "$4/log" | tar -xpf - -C "$3" 2>/dev/null &&
                grep -q '^E ' "$4/log" && break
        else
            "$4/busybox" gzip -dc < "$1" | "$4/carry" tarfilter "$2" "$4/link" "$4/log" | "$4/busybox" tar -xpf - -C "$3" &&
                grep -q '^E ' "$4/log" || return 1
        fi
    done
    "$4/carry" tarlink "$2" "$3" < "$4/log" > "$4/linked" || return 1
}
# delta_room OLD WORK OS [VENDOR]: for the installers (tools/android-install.sh), run from the new image by its busybox
# once the parts are in WORK/root: one line, "delta KB LINKED_KB VENDOR_KB" (WORK/link: the files to link) or "full
# KB 0 VENDOR_KB" (no system to link from, or MU300_DELTA=0; KB from the image's manifest), or "none" (an image
# without these parts: unpacked whole, as before). VENDOR: the device's own files as the installers pack them
# (mu300-vendor-OS.tar.gz), counted by a pass through tarfilter: their binaries that OLD has byte for byte are linked.
delta_room() {
    if ! delta_ready "$2" "$3"; then
        echo none
        return 0
    fi
    # (MU300_DELTA=0: the whole image is unpacked, and the room for that is checked all the same)
    if [ -d "$1" ] && [ "${MU300_DELTA:-1}" != 0 ]; then _dr=delta; delta_plan "$1" "$2/lines" "$2" "$2/carry" > "$2/kb" || return 1
    else _dr=full; : > "$2/link"; delta_kb "$2/link" "$2/lines" > "$2/kb" || return 1; fi
    _dv=0
    if [ -n "${4:-}" ]; then
        _dl='*'; [ "$_dr" = delta ] || { _dl=$2/link; : > "$_dl"; }
        "$2/busybox" gzip -dc < "$4" | "$2/carry" tarfilter "$1" "$_dl" "$2/vlog" > /dev/null || return 1
        _dv=$(sed -n 's/^E [0-9]* \([0-9]*\)$/\1/p' "$2/vlog")
        [ -n "$_dv" ] || return 1
    fi
    echo "$_dr $(cat "$2/kb") $_dv"
}
# --- delta end

# --- diff begin
# A release also carries, for each image, its diff from each of the five releases before it (tools/make-diffs.sh,
# tools/image-diff.py; ported from kanoqwq/mu300-linux b8d4f222, fb0b28e7): the new image without the files the
# older image had as they are, in programs and libraries. Its checksum is in the release's SHA256SUMS with every
# other file's, so it is downloaded and checked - the signature of SHA256SUMS too - as the whole image is
# (fetch_verified), and nothing of it is used before that. A device whose installed image is the diff's base downloads
# it instead of the image; once every download is done, diff_unpack makes the new system from it (the delta block's
# unpack), takes the files it left out from the installed system where that has them byte for byte, and keeps the
# result only when it is, entry for entry, what the release's signed manifest of the image says (mu300-carry
# manifest). Otherwise it is removed, and the whole image downloaded and unpacked as before. What follows the unpack
# is the same for both: the user's files, the accounts, the vendor files, the extras, the VPN and its kill switch
# (never part of an image or a diff), the previous system kept for a rollback. MU300_DIFF=0: always the whole image.
# image_kind ASSET: the image a release file of a root filesystem is (its manifest's second word)
image_kind() {
    case $1 in
        mu300-ubuntu-rootfs.*) echo ubuntu-24.04 ;; mu300-ubuntu-26.04-rootfs.*) echo ubuntu-26.04 ;;
        mu300-openwrt-rootfs.*) echo openwrt ;; mu300-openwrt-luci-rootfs.*) echo openwrt-luci ;; *) return 1 ;;
    esac
}
# diff_asset OS: the release file that is the diff from the image installed in OS (its own manifest says which) to
# this release's image of OS; status 1 when there is none to ask for (no manifest; another image, as Ubuntu 24.04
# moving to 26.04)
diff_asset() {
    _dh=$(gzip -dc < "$DISK/$1/etc/mu300/image-manifest.gz" 2>/dev/null | head -n 1)
    _da=$(rootfs_asset "$1")
    # shellcheck disable=SC2086
    set -- $_dh
    [ "$#" = 4 ] && [ "$1 $2" = "mu300-image-manifest 1" ] && [ "$3" = "$(image_kind "$_da")" ] && tag_ok "$4" || return 1
    echo "${_da%.tar.gz}.diff-$4.tar.gz"
}
# diff_fetch TAG OS: the diff for OS and the image's manifest in $STAGE, both checked against the release's
# SHA256SUMS; status 1 when the whole image is to be downloaded (no such diff, MU300_DIFF=0, a failed download - a
# file that does not match its checksum is never kept)
diff_fetch() {
    [ "${MU300_DIFF:-1}" != 0 ] && _fd=$(diff_asset "$2") || return 1
    _fm=$(rootfs_asset "$2"); _fm=${_fm%.tar.gz}.manifest.gz
    fetch_verified "$1" "$_fd" 2>/dev/null; _fr=$?
    [ "$_fr" = 0 ] || {
        rm -f "$STAGE/$_fd"
        [ "$_fr" = 2 ] || echo "$2: the diff $_fd could not be had: the whole image is downloaded"
        return 1
    }
    fetch_verified "$1" "$_fm" || { rm -f "$STAGE/$_fd"; return 1; }
    _fb=${_fd##*.diff-}
    echo "$2: only what changed since ${_fb%.tar.gz}: $(( $(fsize "$STAGE/$_fd") / 1048576 + 1 )) MB"
}
# diff_unpack OS TAG: DISK/OS.new made from the staged diff and the installed system, and checked against the
# release's signed manifest of the image. Status 1, with DIFF_WHY, when it is not that image: nothing is left of it
DIFF_WHY= DIFF_NEW=
diff_unpack() {
    _uo=$1 _ut=$2
    _uf=$STAGE/$(diff_asset "$_uo") || { DIFF_WHY="the installed image does not say which it is"; return 1; }
    _um=$(rootfs_asset "$_uo"); _um=$STAGE/${_um%.tar.gz}.manifest.gz
    _old=$DISK/$_uo _new=$DISK/$_uo.new _w=$DISK/.mu300-delta-$_uo
    rm -rf "$_new" "$_w"
    DIFF_NEW="$DIFF_NEW $_new $_w"
    # the new image's own parts, from the diff (they are never left out); its manifest is the release's
    delta_tools "$_uf" "$_w" && delta_ready "$_w" "$_uo" || { DIFF_WHY="it does not bring the parts an update runs"; return 1; }
    cmp -s "$_w/root/etc/mu300/image-manifest.gz" "$_um" || { DIFF_WHY="its manifest is not the release's"; return 1; }
    # the room, as for the image (apply_one)
    if [ "${MU300_DELTA:-1}" != 0 ]; then _dp=$(delta_plan "$_old" "$_w/lines" "$_w" "$_w/carry") || { DIFF_WHY="the installed system could not be compared with it"; return 1; }
    else : > "$_w/link"; _dp=$(delta_kb "$_w/link" "$_w/lines"); fi
    _dneed=$(( $(delta_margin "${_dp% *}") + $(carry_need "$_uo") ))
    _dfree=$(df -Pk "$DISK" | awk 'NR == 2 { print $4 }')
    [ "${_dfree:-0}" -ge "$_dneed" ] ||
        die "$_uo: not enough free space on the Linux partition: $((_dneed / 1024)) MB needed, $((${_dfree:-0} / 1024)) MB free. Nothing was changed. mu300-update clean deletes the kept previous versions; mu300-update apply --no-rollback keeps none, and needs no room for your files"
    delta_unpack "$_uf" "$_old" "$_new" "$_w" || { DIFF_WHY="unpacking it failed"; return 1; }
    # what it is, and the files it left out
    [ -f "$_new/.mu300-diff" ] && [ ! -L "$_new/.mu300-diff" ] && mv "$_new/.mu300-diff" "$_w/head" ||
        { DIFF_WHY="it does not say what it is"; return 1; }
    _dh=$(gzip -dc < "$_old/etc/mu300/image-manifest.gz" 2>/dev/null | head -n 1)
    # shellcheck disable=SC2086
    set -- $_dh
    [ "$#" = 4 ] && [ "$(head -n 1 "$_w/head")" = "mu300-diff 1 $3 $4 $_ut" ] ||
        { DIFF_WHY="it is not the diff from the installed image"; return 1; }
    sed 1d "$_w/head" > "$_w/left"
    # from the installed system: binaries of the program trees as second names of its files (the delta block's
    # rule), the rest copied. A file it does not have as the image had it - changed on the device, or gone - and the
    # diff is no use here
    "$_w/carry" same "$_old" < "$_w/left" > "$_w/same.left" || { DIFF_WHY="the installed system could not be compared with it"; return 1; }
    _dn=$(( $(wc -l < "$_w/left") - $(wc -l < "$_w/same.left") ))
    [ "$_dn" = 0 ] || { DIFF_WHY="$_dn of the files it takes from the installed system are not as $4 had them"; return 1; }
    awk -v L="$_w/fill.link" -v C="$_w/fill.copy" 'FILENAME == ARGV[1] { l[$0] = 1; next }
        { p = substr($0, 3); print p > ((p in l) ? L : C) }' "$_w/link" "$_w/same.left" &&
        touch "$_w/fill.link" "$_w/fill.copy" &&
        "$_w/carry" link "$_old" "$_new" < "$_w/fill.link" > /dev/null &&
        "$_w/carry" copy "$_old" "$_new" < "$_w/fill.copy" > /dev/null || { DIFF_WHY="taking the files from the installed system failed"; return 1; }
    # the new system is the release's image, entry for entry: type, mode, owner, size and content of every one
    gzip -dc < "$_um" > "$_w/want" && "$_w/carry" manifest "$_new" "$3" "$_ut" > "$_w/got" && cmp -s "$_w/want" "$_w/got" &&
        cmp -s "$_new/etc/mu300/image-manifest.gz" "$_um" || { DIFF_WHY="the result is not the release's image"; return 1; }
    echo "$_dp" > "$STAGE/.diff-$_uo.kb"
    rm -rf "$_w" "$_uf"
}
# diffs_unpack TAG OS...: the systems that come as a diff made now, after the downloads and before anything is
# changed: one that does not give the release's image is replaced by the whole image, downloaded here (DIFF_READY: the
# systems whose new system is ready)
DIFF_READY=
diffs_unpack() {
    _st=$1; shift
    for _so in "$@"; do
        _sa=$(rootfs_asset "$_so"); _sd=$(diff_asset "$_so") || continue
        [ ! -s "$STAGE/$_sa" ] && [ -s "$STAGE/$_sd" ] || continue
        say "$_so: unpacking the diff"
        if diff_unpack "$_so" "$_st"; then
            DIFF_READY="$DIFF_READY $_so"
            echo "$_so: the diff gives the release's image"
            continue
        fi
        rm -rf "$DISK/$_so.new" "$DISK/.mu300-delta-$_so" "${STAGE:?}/$_sd"
        echo "$_so: the diff is not used ($DIFF_WHY): the whole image is downloaded"
        fetch_verified "$_st" "$_sa" || fetch_stop $?
        payload_is "$_st" "$_so" || die "nothing was changed"
    done
}
# --- diff end

# The update as it was up to v2026.10.27, which keeps keep_list's places and nothing else of the user's: for a new
# image that does not bring the carry block's parts (one built by hand without mu300-carry), and for
# MU300_UPDATE_KEEP=list, which asks for it (kept for one release, should the new way fail somewhere).
# keep_listed_settings before the vendor files are copied, keep_listed_services after; os, old, new: apply_one's.
keep_listed_settings() {
    # etc/mu300 is kept as a whole (hotspot.conf, vpn.conf, ...), but the version of the image and its package lists
    # belong to the new filesystem: copying the old directory over them made every update report the version it
    # replaced
    image_own_save "$new" || { rm -rf "$new"; die "$os: could not read the new image, nothing was changed"; }
    for k in $(keep_list "$os"); do
        [ -e "$old/$k" ] || continue
        mkdir -p "$new/$(dirname "$k")"
        rm -rf "$new/$k.image"
        [ "$k" = etc/config ] && [ -d "$new/$k" ] && mv "$new/$k" "$new/$k.image"
        rm -rf "$new/$k"
        cp -a "$old/$k" "$new/$k"
        # OpenWrt's settings are the old system's, plus the files of the image's own packages the old one did not
        # have (as sysupgrade keeps them): copied whole, the old etc/config dropped e.g. /etc/config/sqm of a
        # package the new image brought, and its LuCI page failed with "uci/get: Resource not found"
        if [ -d "$new/$k.image" ]; then
            copy_missing "$new/$k.image" "$new/$k" || echo "$os: could not add the image's new settings files" >&2
            rm -rf "$new/$k.image"
            # the stray files of v2026.10.18 (the old system's, or that image's own) do not stay
            stale_config_clean "$new"
        fi
    done
    merge_accounts "$old" "$new" || echo "$os: could not carry the accounts over; the image's default password applies" >&2
    image_own_restore "$new" || { rm -rf "$new"; die "$os: could not write the new image's version, nothing was changed"; }
}
keep_listed_services() {
    # services enabled by hand (the links point into the system, so test with -L)
    if [ "$os" = ubuntu ]; then
        for w in "$old"/etc/systemd/system/*.wants; do
            [ -d "$w" ] || continue
            t=${w##*/}
            for l in "$w"/*; do
                [ -L "$l" ] || continue
                u=${l##*/}
                [ -L "$new/etc/systemd/system/$t/$u" ] && continue
                [ -e "$new/etc/systemd/system/$u" ] || [ -e "$new/usr/lib/systemd/system/$u" ] || continue
                mkdir -p "$new/etc/systemd/system/$t"
                cp -a "$l" "$new/etc/systemd/system/$t/$u"
            done
        done
    else
        for l in "$old"/etc/rc.d/*; do
            [ -L "$l" ] || continue
            u=${l##*/}
            [ -L "$new/etc/rc.d/$u" ] && continue
            # only for a service the new system has (as the installers do): the one of a package it does not have
            # comes back with the package (mu300-user-packages)
            [ -x "$new/etc/init.d/${u#[SK][0-9][0-9]}" ] || continue
            cp -a "$l" "$new/etc/rc.d/$u" 2>/dev/null || true
        done
    fi
    # the packages installed on the device: written down, their settings set aside, put back at the first boot
    say "$os: packages installed on the device"
    upk_record "$old" "$new" "$os" || { rm -rf "$new"; die "$os: could not write down the packages installed on the device, nothing was changed"; }
    rm -rf "$new/.mu300-image"
}

apply_one() {  # apply_one OS TAG
    os=$1 tag=$2
    old=$DISK/$os
    new=$DISK/$os.new
    [ -d "$old" ] || die "$os is not installed"
    tarball=$(rootfs_asset "$os")
    tmp=$STAGE
    # made from the diff already (diffs_unpack), and checked against the release's manifest of the image
    ready=; case " $DIFF_READY " in *" $os "*) [ -d "$new" ] && ready=1 ;; esac
    # downloaded and checked in apply() already, together with everything else this update needs
    [ -n "$ready" ] || [ -s "$tmp/$tarball" ] || die "$tarball was not downloaded"

    say "$os: unpacking"
    # (what is being made goes when the run ends before the switch, however it ends: unpack_abort, the EXIT trap)
    work=$DISK/.mu300-delta-$os
    UNPACKING="$new $work"
    [ -n "$ready" ] || rm -rf "$new" "$work"
    # Only what changed is written (the delta block): the files of the new image that this system has byte for byte
    # become second names of its own. The room it takes is known before anything is written, and checked again here
    # with the new image's own helper (apply counted with this system's before the download).
    delta=
    if [ -n "$ready" ]; then
        _dp=$(cat "$STAGE/.diff-$os.kb" 2>/dev/null) || _dp='0 0'
        _dl=${_dp#* }; [ "$_dl" -gt 0 ] 2>/dev/null && delta=1
        echo "$os: made from the diff; $((_dl / 1024)) MB of it are files of this system that did not change"
    elif [ "${MU300_DELTA:-1}" != 0 ] && delta_tools "$tmp/$tarball" "$work" && delta_ready "$work" "$os"; then
        _dp=$(delta_plan "$old" "$work/lines" "$work" "$work/carry") || { rm -rf "$work"; die "$os: could not compare the new image with the installed system, nothing was changed"; }
        _dk=${_dp% *}; _dl=${_dp#* }
        _dneed=$(( $(delta_margin "$_dk") + $(carry_need "$os") ))
        _dfree=$(df -Pk "$DISK" | awk 'NR == 2 { print $4 }')
        if [ "${_dfree:-0}" -lt "$_dneed" ]; then
            rm -rf "$work" "$STAGE"
            die "$os: not enough free space on the Linux partition: $((_dneed / 1024)) MB needed ($((_dk / 1024)) MB of the new release's files that are not in the installed system as they are, the rest a copy of what you added for the previous version kept for a rollback), $((${_dfree:-0} / 1024)) MB free. Nothing was changed (the downloaded files were removed). mu300-update clean deletes the kept previous versions; mu300-update apply --no-rollback keeps none, and needs no room for your files"
        fi
        delta=1
        echo "$os: $((_dl / 1024)) MB of the new release are in this system as they are and are not written again; $((_dk / 1024)) MB are written"
        delta_unpack "$tmp/$tarball" "$old" "$new" "$work" || { rm -rf "$new" "$work" "$tmp/$tarball"; die "unpacking failed, nothing was changed"; }
    else
        rm -rf "$work"; mkdir -p "$new"
        untar -xzpf "$tmp/$tarball" -C "$new" || { rm -rf "$new" "$tmp/$tarball"; die "unpacking failed, nothing was changed"; }
    fi
    rm -rf "$work"
    rm -f "$tmp/$tarball" "$STAGE/.diff-$os.kb"
    [ -x "$new/sbin/init" ] || [ -L "$new/sbin/init" ] || [ -x "$new/bin/busybox" ] || { rm -rf "$new"; die "the unpacked system looks wrong, nothing was changed"; }

    # Everything of the user's goes into the new system (the carry block, run from the new image), with the accounts
    # and the list of the packages to install again; CARRY_MODE=link (apply --no-rollback) when the old system is not
    # kept beside the new one.
    say "$os: carrying your files over, and the vendor files"
    carried=
    if [ "${MU300_UPDATE_KEEP:-all}" != list ] && carry_ready "$new"; then
        carry_run "$old" "$new" "$os" "${CARRY_MODE:-copy}"; r=$?
        case $r in
            0) carried=1 ;;
            3) rm -rf "$new"
               die "$os: nothing was changed. Make room (mu300-update clean deletes the kept previous versions), or update without keeping the previous system for a rollback, which needs no room for your files: mu300-update apply --no-rollback" ;;
            *) rm -rf "$new"
               die "$os: carrying your files over failed, nothing was changed (MU300_UPDATE_KEEP=list mu300-update apply updates as before the first release with a four-field tag: only the settings an update always kept)" ;;
        esac
    elif [ "${MU300_UPDATE_KEEP:-all}" != list ]; then
        echo "$os: this image does not bring what carries everything over (mu300-carry): keeping the settings an update always kept"
    fi
    [ -n "$carried" ] || keep_listed_settings
    # firmware and the Android userspace come from this device, never from the release
    # then what only <os>.old still has: the updaters of 2026-09-18 to this fix, run from OpenWrt, left the system
    # they put in place without them, so on such a device the only copy is in <os>.old, which this update removes
    # (gaps only, after the main copy; not from <os>.old while it is the running root: that update stops below)
    for v in $(vendor_list "$os"); do
        for from in "$old" "$DISK/$os.old"; do
            [ -d "$from/$v" ] || continue
            [ "$from" = "$old" ] || ! is_root "$from" || continue
            mkdir -p "$new/$v"
            copy_missing "$from/$v" "$new/$v" || { rm -rf "$new"; die "$os: copying the vendor files failed, nothing was changed"; }
        done
    done
    [ -n "$carried" ] || keep_listed_services

    say "$os: switching over"
    sync
    is_root "$DISK/$os.old" && { rm -rf "$new"; die "$os was updated already and is still running the old copy: reboot first"; }
    # the old system goes aside as <os>.old, for a rollback. Carried by link (--no-rollback) its files are the new
    # system's too, so it is no copy to go back to: it goes aside as <os>.broken, which rollback does not offer and
    # the next apply, or clean, removes once it is not the running system any more
    aside=$DISK/$os.old
    if [ -n "$carried" ] && [ "${CARRY_MODE:-copy}" = link ]; then
        aside=$DISK/$os.broken
        is_root "$aside" && { rm -rf "$new"; die "$os was updated already and is still running the old copy: reboot first"; }
        rm -rf "$aside"
    fi
    rm -rf "$DISK/$os.old"
    mv "$old" "$aside" || die "could not move the old system aside"
    mv "$new" "$old" || { mv "$aside" "$old"; die "could not put the new system in place (old one restored)"; }
    UNPACKING=
    sync
    printf '%s: updated %s -> %s\n' "$os" "$(cat "$aside$VERSION_FILE" 2>/dev/null || echo unknown)" "$(cat "$old$VERSION_FILE" 2>/dev/null || echo unknown)"
    # (two names of one file are one file: what changes one of these in place changes both, the delta block)
    [ -z "$delta" ] || [ "$aside" != "$DISK/$os.old" ] ||
        echo "$os: the previous version ($os.old) shares $((_dl / 1024)) MB of programs and libraries that did not change with the new one: replace such a file, never write into it, while the previous version is kept"
    [ "$aside" = "$DISK/$os.old" ] || NO_ROLLBACK="$NO_ROLLBACK $os"
}

# ---- extras -----------------------------------------------------------------------------------------------------
# Optional parts that are not in the images, installed on the Linux partition next to the systems, so both systems use
# one copy and nothing that replaces a system touches it. mu300-extra is the command; the functions are here
# because an update installs and refreshes them too, and the updater of the new release runs before the system
# that has mu300-extra exists. Two kinds:
#   lang         a release asset of mu300-linux, mu300-extra-lang.tar.gz (tools/make-extra.sh: ./name, ./release,
#                ./components, ./languages, ./manifest, ./i18n/<catalogs>), for the release it was published with
#   vpn, vpn-xray, vpn-singbox, vpn-mihomo, vpn-dae   the VPN module, released on its own by
#                github.com/dikeckaan/mu300-linux-vpn under fixed names (mu300-linux-vpn-core.tar.gz for vpn - the
#                core, mu300-vpn without an engine - and mu300-linux-vpn-ENGINE.tar.gz for the engines, SHA256SUMS):
#                ./VERSION, ./components, ./requires ("mu300-linux vYYYY.MM.DD", the oldest system it works with),
#                ./bin/<programs>, ./hooks/link, ./hooks/unlink - which make one system use it (sh hooks/link SYSROOT,
#                "" for the running system), and for vpn ./lib/vpn, ./service, ./etc, so the images carry no mu300-vpn
#                at all. mu300-linux-vpn.tar.gz is vpn as module v1 was, the core with xray and sing-box in it (the
#                bundle, which mu300-extra and mu300-update from before the engine extras download): taken when the
#                core is not to be had (a pinned v1 release, a copy brought by hand), and as the fallback of a set.
EXTRA=$DISK/extra
EXTRAS="vpn lang vpn-mihomo panel vpn-xray vpn-singbox vpn-dae"
# the engines, each an extra of the VPN module
VPN_ENGINE_EXTRAS="vpn-xray vpn-singbox vpn-mihomo vpn-dae"
VPN_REPO=dikeckaan/mu300-linux-vpn
# MU300_VPN_URL: another place with the module's files and SHA256SUMS (a pinned tag: .../releases/download/v1.0.0,
# or a local server)
VPN_URL=${MU300_VPN_URL:-https://github.com/$VPN_REPO/releases/latest/download}
# where an update looks for a module copied onto the device by hand (the tarball and its SHA256SUMS)
VPN_STAGED=$DISK/.mu300-update/vpn
extra_desc() {
    case $1 in
        vpn) echo "the VPN toolkit (mu300-vpn: profiles, kill switch), the module of github.com/$VPN_REPO; the engines are the vpn-* extras, the ones the profiles need come along (about 0.1 MB, with xray 15 MB)" ;;
        lang) echo "LuCI (the web interface) in 40 more languages, the MU300 panel in 29 of them; OpenWrt only (about 2 MB to download, 6 MB installed)" ;;
        vpn-xray) echo "Xray-core and hev-socks5-tunnel, the engine of mu300-vpn's VLESS, VMess, Trojan, Shadowsocks and Xray JSON profiles (about 15 MB to download, 40 MB installed)" ;;
        vpn-singbox) echo "sing-box, the engine of mu300-vpn's sing-box JSON profiles, and of VLESS links behind the kill switch (about 15 MB to download, 40 MB installed)" ;;
        vpn-mihomo) echo "mihomo (Clash.Meta), the engine of mu300-vpn's mihomo profiles, from the same module repository (about 15 MB to download, 40 MB installed)" ;;
        vpn-dae) echo "dae (eBPF transparent proxy) with its geodata, for mu300-vpn's dae profiles; needs a kernel with BTF (mainline) (about 25 MB to download, 60 MB installed)" ;;
        panel) echo "the web panel for Ubuntu: Cockpit (terminal, logs, services) and the MU300 page, on the LAN only (port 9090); Cockpit from Ubuntu's archive (about 12 MB, 45 MB installed), or offline with --from mu300-extra-panel-offline.tar.gz" ;;
    esac
}
extra_asset() { echo "mu300-extra-$1.tar.gz"; }
extra_is_module() { case $1 in vpn|vpn-mihomo|vpn-xray|vpn-singbox|vpn-dae) return 0 ;; esac; return 1; }
# module_asset NAME: the release file of a module extra (vpn-bundle: the vpn extra as the bundle)
module_asset() {
    case $1 in
        vpn) echo mu300-linux-vpn-core.tar.gz ;; vpn-bundle) echo mu300-linux-vpn.tar.gz ;;
        vpn-mihomo|vpn-xray|vpn-singbox|vpn-dae) echo "mu300-linux-$1.tar.gz" ;;
    esac
}
# module_url NAME: where the VPN module's release files are
module_url() { echo "$VPN_URL"; }
# module_what NAME: what the messages call it
module_what() { echo "the VPN module ($VPN_URL)"; }
extra_known() { case " $EXTRAS " in *" $1 "*) return 0 ;; esac; return 1; }
# extra_own NAME: NAME can be an extra of the user's own - one that is not in this list, installed from a file the user
# copied onto the device (mu300-extra install NAME --from FILE). It is never downloaded, never updated by mu300-update,
# and never listed: list, status and version show the extras of the releases, an own extra only when asked by name
# (mu300-extra status NAME). Its tree is a module's (plain names, four levels), it must carry ./manifest, and its
# hooks/link and hooks/unlink run for every system like the VPN module's.
extra_own() {
    extra_known "$1" && return 1
    case $1 in ''|audio|-*|vpn-*|*[!a-z0-9-]*) return 1 ;; esac
    [ ${#1} -le 32 ]
}
extra_installed() {
    for d in "$EXTRA"/*; do
        { [ -d "$d/bin" ] || [ -d "$d/i18n" ]; } && printf '%s ' "${d##*/}"
    done
    return 0
}
extra_release() {
    if [ -f "$EXTRA/$1/release" ]; then cat "$EXTRA/$1/release"
    elif [ -f "$EXTRA/$1/VERSION" ]; then cat "$EXTRA/$1/VERSION"
    else echo unknown; fi
}
# vpn_module_in DIR: DIR is the VPN module (an older vpn extra had the engines only, no mu300-vpn)
vpn_module_in() { [ -f "$1/bin/mu300-vpn" ] && [ -x "$1/bin/mu300-vpn" ]; }

# extra_put NAME DIR: DIR (on the same filesystem) becomes the extra; the one it replaces is removed afterwards.
# Running programs keep their files, as with a system that is updated while it runs.
extra_put() {
    # an earlier swap cut off between its two renames: the old one is still the one there is
    [ -d "$EXTRA/$1" ] || [ ! -d "$EXTRA/.$1.old" ] || mv "$EXTRA/.$1.old" "$EXTRA/$1" || return 1
    rm -rf "$EXTRA/.$1.old"
    if [ -d "$EXTRA/$1" ]; then mv "$EXTRA/$1" "$EXTRA/.$1.old" || return 1; fi
    if ! mv "$2" "$EXTRA/$1"; then
        [ -d "$EXTRA/.$1.old" ] && mv "$EXTRA/.$1.old" "$EXTRA/$1"
        return 1
    fi
    # the panel: Cockpit's packages the old extra kept (an offline install, or what an online one downloaded) go
    # along to a new one that brings none (the release's online extra, which every update installs): without them a
    # device that is offline after an update had no Cockpit until it was online again
    if [ "$1" = panel ] && [ -d "$EXTRA/.$1.old/debs" ] && [ ! -e "$EXTRA/$1/debs" ]; then
        mv "$EXTRA/.$1.old/debs" "$EXTRA/$1/debs" || echo "extra panel: Cockpit's packages of the previous extra were not kept" >&2
    fi
    rm -rf "$EXTRA/.$1.old"
    sync
}

# An extra holds plain files and directories only, under names of its own. It may come from a file someone uploaded
# through the web page, not only from a verified release download, and tar implementations (GNU, busybox) list and
# extract differently, so nothing rests on one check: the listing is checked before anything is unpacked (names,
# and every entry's type), and the unpacked tree is checked again by what is really on disk (find: no link, device,
# FIFO or socket, no file with a second name; for lang every path one of its own) before it is put in place.
# extra_tar_ok TARBALL: the listing - each name relative, without a .. component; each entry a file or directory
extra_tar_ok() {
    _l=$(untar -tzf "$1") || return 1
    [ -n "$_l" ] || return 1
    ! printf '%s\n' "$_l" | LC_ALL=C grep -Eq -- '^/|(^|/)\.\.(/|$)' || return 1
    _v=$(untar -tvzf "$1") || return 1
    # one line per entry (a name with a newline makes a line that is not one), a file or directory each, and no
    # link targets (GNU: "link to", "->"; busybox: "->")
    [ "$(printf '%s\n' "$_v" | wc -l)" = "$(printf '%s\n' "$_l" | wc -l)" ] || return 1
    ! printf '%s\n' "$_v" | cut -c1 | LC_ALL=C grep -vq '^[-d]$' || return 1
    ! printf '%s\n' "$_v" | LC_ALL=C grep -Eq -- ' -> | link to ' || return 1
}
# extra_tree_ok NAME DIR: the unpacked tree, as it is on disk
extra_tree_ok() {
    # (find's own failure fails the check: its output is taken whole, not through a pipe)
    _t=$(find "$2" ! -type f ! -type d) || return 1
    [ -z "$_t" ] || return 1
    _t=$(find "$2" -type f -exec ls -ld {} +) || return 1
    [ -z "$(printf '%s\n' "$_t" | awk '$2 != 1')" ] || return 1
    _t=$(cd "$2" && find .) || return 1
    # the VPN module: plain names, four levels at most (bin/, lib/vpn/, service/systemd/, hooks/, ...)
    if extra_is_module "$1" || extra_own "$1"; then
        ! printf '%s\n' "$_t" | LC_ALL=C grep -Evxq -- "$MODULE_ENTRY"
        return
    fi
    # panel: its four files, bin/, the Cockpit page (cockpit/mu300/<files>) and, offline, Cockpit's packages for each
    # Ubuntu release (debs/<release>/<name>.deb)
    if [ "$1" = panel ]; then
        ! printf '%s\n' "$_t" | LC_ALL=C grep -Evxq -- "$PANEL_ENTRY"
        return
    fi
    # the other extras: their four files and programs in bin/, nothing else (whatever a tar did to the names)
    if [ "$1" != lang ]; then
        ! printf '%s\n' "$_t" | LC_ALL=C grep -Evxq -- '\.|\./(name|release|components|manifest|bin|bin/[A-Za-z0-9._+-]+)'
        return
    fi
    ! printf '%s\n' "$_t" | LC_ALL=C grep -Evxq -- "$LANG_ENTRY" || return 1
    # the catalogs are files, never directories under a catalog's name
    _t=$(find "$2/i18n" -mindepth 1 ! -type f) || return 1
    [ -z "$_t" ]
}
# extra_manifest_ok NAME DIR: ./manifest (sha256sum lines, "HASH  ./path") lists every plain file of the tree but
# itself, and each one has that hash. The lang extra and an own extra (extra_own) must carry one; for the others it
# is checked when there is one (extras from before it have none). With a download the manifest is covered by the release's SHA256SUMS, which
# the whole tarball was checked against.
extra_manifest_ok() {
    _m=$2/manifest
    [ -f "$_m" ] || { [ "$1" != lang ] && ! extra_own "$1"; return; }
    ! LC_ALL=C grep -Evxq -- '[0-9a-f]{64}  \./[A-Za-z0-9._+/-]+' "$_m" || return 1
    _want=$(cut -c67- "$_m" | LC_ALL=C sort) || return 1
    _have=$(cd "$2" && find . -type f ! -path ./manifest | LC_ALL=C sort) || return 1
    [ -n "$_want" ] && [ "$_want" = "$_have" ] || return 1
    (cd "$2" && sha256sum -c manifest >/dev/null 2>&1)
}
# extra_size_ok NAME TARBALL: unpacked, it fits (a small archive must not fill the Linux partition every system
# lives on): at most 32 MB and 1000 entries for lang, 600 MB for the others. Counted by decompressing, which every
# gzip does alike, not from a listing format.
extra_size_ok() {
    case $1 in lang) _max=$((32 << 20)) ;; *) _max=$((600 << 20)) ;; esac
    _sz=$(gzip -dc < "$2" 2>/dev/null | head -c $((_max + 1)) | wc -c) || return 1
    [ "$_sz" -le "$_max" ] || return 1
    [ "$1" != lang ] || [ "$(untar -tzf "$2" | wc -l)" -le 1000 ]
}
# lang_tar_ok TARBALL: the lang extra holds only its four files and catalogs
LANG_ENTRY='\.|\./|\./(name|release|components|languages|manifest|i18n/?|i18n/[a-z0-9-]+\.[a-z]{2,3}(-[a-z]{2})?\.lmo)'
lang_tar_ok() {
    _l=$(untar -tzf "$1") || return 1
    [ -n "$_l" ] && ! printf '%s\n' "$_l" | LC_ALL=C grep -Evxq -- "$LANG_ENTRY"
}
# a language line of the lang extra: the uci key (LuCI's code, - as _), a tab, the name the list shows (no quote,
# backslash, $, backquote, <, >, & or control character: it goes into /etc/config/luci, into JSON and into a page)
# ./release: a tag
EXTRA_RELEASE='[A-Za-z0-9._-]{1,40}'
PANEL_ENTRY='\.|\./(name|release|components|manifest|bin|bin/mu300-panel|cockpit|cockpit/mu300|cockpit/mu300/[A-Za-z0-9_-][A-Za-z0-9._-]*|debs|debs/[0-9]{2}\.[0-9]{2}|debs/[0-9]{2}\.[0-9]{2}/[A-Za-z0-9][A-Za-z0-9._+~-]*\.deb)'
MODULE_ENTRY='\.|\./[A-Za-z0-9_+-][A-Za-z0-9._+-]*(/[A-Za-z0-9_+-][A-Za-z0-9._+-]*){0,3}'
LANG_LINE='[a-z]{2,3}(_[a-z]{2})?	[^	"`$<>&\\'"'"'[:cntrl:]]{1,100}'

# extra_unpack NAME TARBALL [FOR]: install a downloaded (and verified) extra; the old one stays when anything is wrong.
# FOR: the mu300-linux release the systems will run, which a module's ./requires must not be newer than.
# The tarball is read once, into a directory only root can enter, and checked and unpacked from that copy: a file
# swapped at TARBALL's path after the copy (a /tmp upload, a link planted there) changes nothing.
extra_unpack() {
    case $1 in ''|*[!a-z0-9-]*) echo "extra: bad name '$1'" >&2; return 1 ;; esac
    _in=$EXTRA/.$1.in
    rm -rf "$_in"; mkdir -p "$EXTRA" && mkdir -m 700 "$_in" || return 1
    if ! cat < "$2" > "$_in/x.tar.gz" 2>/dev/null; then
        rm -rf "$_in"; echo "extra $1: $2 is not readable" >&2; return 1
    fi
    if ! extra_size_ok "$1" "$_in/x.tar.gz"; then
        rm -rf "$_in"; echo "extra $1: $2 is too large unpacked" >&2; return 1
    fi
    if ! extra_tar_ok "$_in/x.tar.gz" || { [ "$1" = lang ] && ! lang_tar_ok "$_in/x.tar.gz"; }; then
        rm -rf "$_in"; echo "extra $1: $2 is not a $1 extra (links, odd names or unexpected files in it)" >&2; return 1
    fi
    # unpacked into a new, empty directory only root can enter; it becomes the extra only after the checks
    _new=$EXTRA/.$1.new
    rm -rf "$_new"; mkdir -m 700 "$_new" || { rm -rf "$_in"; return 1; }
    # -o: owned by root (who unpacks), not by the ids in the archive
    _ok=1; untar -xozf "$_in/x.tar.gz" -C "$_new" 2>/dev/null || _ok=
    rm -rf "$_in"
    if [ -z "$_ok" ]; then
        rm -rf "$_new"; echo "extra $1: $2 is not a readable tar.gz" >&2; return 1
    fi
    if ! extra_tree_ok "$1" "$_new"; then
        rm -rf "$_new"; echo "extra $1: $2 unpacked to links or unexpected files; not installed" >&2; return 1
    fi
    if ! extra_manifest_ok "$1" "$_new"; then
        rm -rf "$_new"; echo "extra $1: $2 does not match its manifest; not installed" >&2; return 1
    fi
    # modes are ours too: the disk is shared with Ubuntu's users and mounted without nosuid. Catalogs are plain
    # read-only files; programs keep their execute bits, never set-id or writable by others.
    chown -R 0:0 "$_new" 2>/dev/null
    if [ "$1" = lang ]; then
        find "$_new" -type d -exec chmod 755 {} + && find "$_new" -type f -exec chmod 644 {} +
    else
        chmod -R u-s,g-s,go-w "$_new"
    fi || { rm -rf "$_new"; echo "extra $1: could not set its file modes" >&2; return 1; }
    chmod 755 "$_new"
    if extra_is_module "$1"; then
        _rel=$_new/VERSION
    else
        _rel=$_new/release
        if [ "$(cat "$_new/name" 2>/dev/null)" != "$1" ]; then
            rm -rf "$_new"; echo "extra $1: $2 is not the $1 extra" >&2; return 1
        fi
    fi
    if ! LC_ALL=C grep -Eqx -- "$EXTRA_RELEASE" "$_rel" 2>/dev/null || [ "$(wc -l < "$_rel")" -ne 1 ]; then
        rm -rf "$_new"; echo "extra $1: $2 has no valid ${_rel##*/}" >&2; return 1
    fi
    if extra_is_module "$1"; then
        # an older vpn extra (the engines alone) is not the module: the images have no mu300-vpn of their own any more
        if [ "$1" = vpn ] && { ! vpn_module_in "$_new" || [ ! -f "$_new/hooks/link" ] || [ ! -f "$_new/hooks/unlink" ]; }; then
            rm -rf "$_new"; echo "extra $1: $2 is not the VPN module (bin/mu300-vpn, hooks/link or hooks/unlink missing)" >&2; return 1
        fi
        _need=$(module_needs "$_new")
        if ! version_ok "$_need" "${3:-}"; then
            rm -rf "$_new"
            echo "extra $1: $2 needs mu300-linux $_need or newer, and the system is ${3:-unknown}: update it first (mu300-update apply)" >&2
            return 1
        fi
    fi
    _n=0
    if [ "$1" = lang ]; then
        for _f in "$_new"/i18n/*.lmo; do [ -f "$_f" ] && [ ! -L "$_f" ] && _n=$((_n + 1)); done
        if [ "$_n" = 0 ] || ! [ -s "$_new/languages" ] || LC_ALL=C grep -Evxq -- "$LANG_LINE" "$_new/languages"; then
            rm -rf "$_new"; echo "extra $1: no catalogs or no valid language list in $2" >&2; return 1
        fi
    else
        for _f in "$_new"/bin/*; do [ -f "$_f" ] && [ -x "$_f" ] && _n=$((_n + 1)); done
        if [ "$_n" = 0 ]; then rm -rf "$_new"; echo "extra $1: no programs in $2" >&2; return 1; fi
    fi
    extra_put "$1" "$_new" || { rm -rf "$_new"; echo "extra $1: could not put it in place" >&2; return 1; }
}

# does the system at ROOT use the VPN? (only the switch is read, never the rest of the file)
extra_vpn_wanted() { grep -q '^ENABLE=1' "$1/etc/mu300/vpn.conf" 2>/dev/null; }
# vpn_killswitch_wanted ROOT: the VPN on with its kill switch in the system at ROOT - a copy of lib/vpn-orphan.sh's
# (this updater runs before the system that has that file exists; tests/test_vpn_hooks.py holds both to one matrix)
vpn_conf_value() {
    [ -r "$1" ] || return 0
    sed -n "s/^$2=//p" "$1" 2>/dev/null | tail -n1 | sed "s/[[:space:]]#.*//; s/[\"' ]//g"
}
vpn_killswitch_wanted() {
    [ "$(vpn_conf_value "${1:-}/etc/mu300/vpn.conf" ENABLE)" = 1 ] || return 1
    if [ -d "${1:-}/etc/mu300/vpn/profiles" ] && [ -r "${1:-}/etc/mu300/vpn/settings" ]; then
        _vks=$(vpn_conf_value "${1:-}/etc/mu300/vpn/settings" KILL_SWITCH)
    else
        _vks=$(vpn_conf_value "${1:-}/etc/mu300/vpn.conf" KILL_SWITCH)
    fi
    [ "$_vks" != 0 ]
}

# ---- the VPN module -----------------------------------------------------------------------------------------------
# module_needs DIR: the mu300-linux release the module in DIR needs (./requires: "mu300-linux vYYYY.MM.DD", or
# vYYYY.MM.DD.N; none: any)
module_needs() { awk '$1 == "mu300-linux" {print $2; exit}' "$1/requires" 2>/dev/null; }
# version_ok NEED HAVE: HAVE is NEED or newer (newer: the release tags, vYYYY.MM.DD and vYYYY.MM.DD.N, FINDINGS
# 125); a system that is no release (a build of one's own, "dev", unknown) is not judged. Anything else that starts
# with v is compared as text, as it always was.
version_ok() {
    [ -n "$1" ] || return 0
    case $2 in v[0-9]*) ;; *) return 0 ;; esac
    if tag_ok "$1" && tag_ok "$2"; then ! newer "$1" "$2"; return; fi
    [ "$(printf '%s\n%s\n' "$1" "$2" | sort | tail -n1)" = "$2" ]
}
# sha_ok HASH: a SHA-256 as sha256sum writes it (64 lowercase hex digits); nothing else ever counts as a hash, so an
# empty or broken value can never compare equal to anything
sha_ok() { case $1 in ''|*[!0-9a-f]*) return 1 ;; esac; [ ${#1} -eq 64 ]; }
# sha_of FILE: its SHA-256, or nothing and 1 (no sha256sum, a read error): a failure is never a hash
sha_of() { _so=$(sha256sum "$1" 2>/dev/null) || return 1; _so=${_so%% *}; sha_ok "$_so" || return 1; printf '%s\n' "$_so"; }
# sums_want SUMS NAME: the hash SUMS lists for NAME, only when it is a hash
sums_want() { _sw=$(awk -v f="$2" '$2 == f || $2 == "*" f {print $1; exit}' "$1" 2>/dev/null); ! sha_ok "$_sw" || printf '%s\n' "$_sw"; }

# The module's tarball, checked, as MODULE_FILE (its hash: MODULE_SHA). Status 0 with a file, 3 when the installed
# one is that release's already (nothing downloaded), 1 when it cannot be had (offline, GitHub down), 2 when what
# there is fails its check.
# What is checked is what is installed: every tarball (and the SHA256SUMS it is checked against) is first copied, as a
# regular file and not through a link, into a directory of this run's own (MODULE_VDIR, 0700, root's), and the hash is
# taken of that copy, which is the file extra_unpack reads. A file swapped at the source after the check - in a --from
# directory, the staging directory or a download directory another process can write - changes nothing.
# module_asset_ok NAME: a release file name of the module, as module_asset gives them and nothing else
module_asset_ok() {
    case $1 in
        mu300-linux-vpn.tar.gz|mu300-linux-vpn-*.tar.gz) case ${1%.tar.gz} in *[!a-z0-9-]*) return 1 ;; esac ;;
        *) return 1 ;;
    esac
}
# module_vdir: MODULE_VDIR made (once per run), fresh and private
MODULE_VDIR=
module_vdir() {
    [ -n "$MODULE_VDIR" ] && [ -d "$MODULE_VDIR" ] && [ ! -L "$MODULE_VDIR" ] && return 0
    mkdir -p "$EXTRA" || return 1
    # (one left by a run that died: nothing reads it again)
    rm -rf "$EXTRA"/.verified.*
    MODULE_VDIR=$EXTRA/.verified.$$
    ( umask 077; mkdir -m 700 "$MODULE_VDIR" ) || { MODULE_VDIR=; return 1; }
}
module_vdir_clean() { [ -z "$MODULE_VDIR" ] || rm -rf "$MODULE_VDIR"; MODULE_VDIR=; }
# module_copy SRC NAME: SRC - a regular file, not a symbolic link - copied to MODULE_VDIR/NAME (prints that path)
module_copy() {
    [ -f "$1" ] && [ ! -L "$1" ] || { echo "$1 is not a regular file (a link or something else): not used" >&2; return 2; }
    module_asset_ok "$2" || [ "$2" = SHA256SUMS ] || { echo "not a file name of a module: refused" >&2; return 2; }
    [ -n "$MODULE_VDIR" ] && [ -d "$MODULE_VDIR" ] || { echo "no private directory to check $2 in" >&2; return 1; }
    rm -f "$MODULE_VDIR/$2"
    ( umask 077; cat < "$1" > "$MODULE_VDIR/$2" ) 2>/dev/null || { rm -f "$MODULE_VDIR/$2"; echo "cannot read $1" >&2; return 2; }
    printf '%s\n' "$MODULE_VDIR/$2"
}
# module_from DIR|FILE NAME [ASSET]: a copy brought onto the device. A directory must hold the tarball and its
# SHA256SUMS and is verified; a file is checked against a SHA256SUMS next to it that lists it (else it is the user's
# own choice).
module_from() {
    # (here, not in module_copy: that runs in a command substitution, whose MODULE_VDIR would be lost)
    module_vdir || { echo "cannot create a private directory under $EXTRA" >&2; return 1; }
    if [ -d "$1" ]; then
        _a=${3:-$(module_asset "$2")}
        module_asset_ok "$_a" || { echo "not a file name of a module: refused" >&2; return 2; }
        [ -s "$1/$_a" ] || { echo "no $_a in $1" >&2; return 2; }
        _sc=$(module_copy "$1/SHA256SUMS" SHA256SUMS) ||
            { echo "$1/SHA256SUMS is missing or not a regular file: $_a not installed unverified" >&2; return 2; }
        _w=$(sums_want "$_sc" "$_a")
        [ -n "$_w" ] || { echo "$1/SHA256SUMS does not list $_a: not installed unverified" >&2; return 2; }
        _c=$(module_copy "$1/$_a" "$_a") || return 2
        [ "$(sha_of "$_c")" = "$_w" ] || { rm -f "$_c"; echo "$1/$_a does not match its SHA256SUMS" >&2; return 2; }
        MODULE_FILE=$_c MODULE_SHA=$_w
        return 0
    fi
    [ -s "$1" ] || { echo "$1 not found" >&2; return 2; }
    case $1 in */*) _d=${1%/*}; [ -n "$_d" ] || _d=/ ;; *) _d=. ;; esac
    _w=
    if _sc=$(module_copy "$_d/SHA256SUMS" SHA256SUMS 2>/dev/null); then _w=$(sums_want "$_sc" "${1##*/}"); fi
    # A local build without SHA256SUMS needs explicit permission to install unchecked.
    _uv=MU300_VPN_UNVERIFIED
    if [ -z "$_w" ] && [ "$(eval "echo \${$_uv:-}")" != 1 ]; then
        echo "no SHA256SUMS next to $1 lists it: not installed unverified (copy the release's SHA256SUMS next to it, or $_uv=1 for a build of your own)" >&2
        return 2
    fi
    _c=$(module_copy "$1" "$(module_asset "$2")") || return 2
    MODULE_SHA=$(sha_of "$_c") || { rm -f "$_c"; echo "cannot compute the SHA-256 of $1 (sha256sum): not installed" >&2; return 2; }
    [ -z "$_w" ] || [ "$MODULE_SHA" = "$_w" ] || { rm -f "$_c"; echo "$1 does not match $_d/SHA256SUMS" >&2; return 2; }
    [ -n "$_w" ] || echo "note: $1 is installed unverified ($_uv=1)" >&2
    MODULE_FILE=$_c
}
# module_download NAME DIR [ASSET]: the module's latest release (VPN_URL) into DIR, checked against that release's
# SHA256SUMS (fetched every time: under releases/latest the same name is a new file with every release)
module_download() {
    _a=${3:-$(module_asset "$1")}
    module_asset_ok "$_a" || { echo "not a file name of a module: refused" >&2; return 1; }
    module_vdir || { echo "cannot create a private directory under $EXTRA" >&2; return 1; }
    mkdir -p "$2" || return 1
    _mu=$(module_url "$1")
    _s=$(fetch_stdout "$_mu/SHA256SUMS") && [ -n "$_s" ] ||
        { echo "cannot download SHA256SUMS of $(module_what "$1")" >&2; return 1; }
    _w=$(printf '%s\n' "$_s" | awk -v f="$_a" '$2 == f || $2 == "*" f {print $1; exit}')
    sha_ok "$_w" || { echo "$_a is not part of the release of $(module_what "$1"), or its SHA256SUMS line is no hash" >&2; return 1; }
    MODULE_SHA=$_w
    # the installed one is this release's: nothing to download
    [ -d "$EXTRA/$1/bin" ] && [ "$(cat "$EXTRA/.$1.sha256" 2>/dev/null)" = "$_w" ] && return 3
    for _try in 1 2 3; do
        if [ -s "$2/$_a" ] || { rm -f "$2/$_a"; fetch_file "$_mu/$_a" "$2/$_a"; }; then
            if _c=$(module_copy "$2/$_a" "$_a") && [ "$(sha_of "$_c")" = "$_w" ]; then
                rm -f "$2/$_a"; MODULE_FILE=$_c; return 0
            fi
            [ -z "${_c:-}" ] || rm -f "$_c"
        fi
        rm -f "$2/$_a"
    done
    echo "downloading $_a failed" >&2
    return 1
}

# module_get NAME DIR [FROM]: FROM (a file or a directory) when given, else the download into DIR. For vpn, the core
# (mu300-linux-vpn-core.tar.gz), else the bundle (mu300-linux-vpn.tar.gz: a release or a copy from before the
# engine extras); MODULE_BUNDLE=1 when what it got (or what is installed, status 3) carries xray and sing-box.
# module_get vpn-bundle DIR [FROM]: the bundle alone, as the vpn extra (FROM a directory)
module_get() {
    MODULE_FILE= MODULE_SHA= MODULE_BUNDLE=
    if [ "$1" = vpn-bundle ]; then
        _mg=0
        if [ -n "${3:-}" ]; then module_from "$3" vpn "$(module_asset vpn-bundle)" || _mg=$?
        else module_download vpn "$2" "$(module_asset vpn-bundle)" || _mg=$?; fi
        case $_mg in 0) MODULE_BUNDLE=1 ;; 3) [ ! -x "$EXTRA/vpn/bin/xray" ] || MODULE_BUNDLE=1 ;; esac
        return "$_mg"
    fi
    if [ "$1" != vpn ] || { [ -n "${3:-}" ] && [ ! -d "$3" ]; }; then
        if [ -n "${3:-}" ]; then module_from "$3" "$1"; else module_download "$1" "$2"; fi
        _mg=$?
    else
        _mg=0
        if [ -n "${3:-}" ]; then module_from "$3" vpn 2>/dev/null || _mg=$?; else module_download vpn "$2" 2>/dev/null || _mg=$?; fi
        if [ "$_mg" != 0 ] && [ "$_mg" != 3 ]; then
            _mg2=0
            if [ -n "${3:-}" ]; then module_from "$3" vpn "$(module_asset vpn-bundle)" || _mg2=$?
            else module_download vpn "$2" "$(module_asset vpn-bundle)" || _mg2=$?; fi
            # (the core's status when neither is to be had: offline stays offline)
            case $_mg2 in 0|3) _mg=$_mg2 ;; esac
        fi
    fi
    if [ "$1" = vpn ]; then
        case $_mg in
            0) ! untar -tzf "$MODULE_FILE" 2>/dev/null | grep -qx '\./bin/xray' || MODULE_BUNDLE=1 ;;
            3) [ ! -x "$EXTRA/vpn/bin/xray" ] || MODULE_BUNDLE=1 ;;
        esac
    fi
    return "$_mg"
}
# module_install NAME FILE SHA FOR: extra_unpack, and the hash kept, to know the installed release next time
module_install() {
    extra_unpack "$1" "$2" "$4" || return 1
    printf '%s\n' "$3" > "$EXTRA/.$1.sha256"
}

# ---- which engines the device needs ------------------------------------------------------------------------------
# vpn_type_engine TYPE: the engine extra of a profile type (wireguard and openvpn are the system's packages)
vpn_type_engine() {
    case $1 in xray) echo vpn-xray ;; sing-box) echo vpn-singbox ;; mihomo) echo vpn-mihomo ;; dae) echo vpn-dae ;; esac
}
# vpn_engines_of ROOT: the engine extras the profiles of the system at ROOT run on (every profile, not only the
# active one: profile use must not find its engine gone); a vpn.conf with a link and no profile store (never
# migrated) runs on xray, or on sing-box behind the kill switch
vpn_engines_of() {
    if [ -d "$1/etc/mu300/vpn/profiles" ]; then
        for _vm in "$1"/etc/mu300/vpn/profiles/*/meta; do
            [ -r "$_vm" ] && vpn_type_engine "$(vpn_conf_value "$_vm" TYPE)"
        done
    elif grep -q '^VLESS_URI=' "$1/etc/mu300/vpn.conf" 2>/dev/null; then
        echo vpn-xray; echo vpn-singbox
    fi
    return 0
}
# vpn_engine_have X: the device runs on engine X now - its extra, or the vpn extra that carries it (module v1, the
# bundle)
vpn_engine_have() {
    [ -d "$EXTRA/$1/bin" ] && return 0
    case $1 in vpn-xray) [ -x "$EXTRA/vpn/bin/xray" ] ;; vpn-singbox) [ -x "$EXTRA/vpn/bin/sing-box" ] ;; *) return 1 ;; esac
}
# vpn_engines_wanted: the engine extras the VPN module comes with - every one the device has now (installed, or in
# the vpn extra, which v1 and the bundle are: all of v1's engines stay), every one a profile of an installed system
# needs, and for a first install MU300_VPN_ENGINES (default vpn-xray; none: the core alone)
vpn_engines_wanted() {
    {
        for _x in $VPN_ENGINE_EXTRAS; do vpn_engine_have "$_x" && echo "$_x"; done
        for _o in $(installed_systems); do vpn_engines_of "$DISK/$_o"; done
        [ -z "${MU300_SYSROOT:-}" ] || vpn_engines_of "$MU300_SYSROOT"
        if [ ! -d "$EXTRA/vpn/bin" ]; then
            for _x in $(printf '%s' "${MU300_VPN_ENGINES-vpn-xray}" | tr ',' ' '); do
                case $_x in xray|singbox|sing-box|mihomo|dae) _x=vpn-$_x ;; esac
                [ "$_x" != vpn-sing-box ] || _x=vpn-singbox
                case " $VPN_ENGINE_EXTRAS " in *" $_x "*) echo "$_x" ;; esac
            done
        fi
    } | sort -u
}
# vpn_engine_in_use X [ROOT...]: a system (default: every installed one) has the VPN on with an active profile that
# runs on engine X
vpn_engine_in_use() {
    _x=$1; shift
    [ $# -gt 0 ] || set -- $(for _o in $(installed_systems); do echo "$DISK/$_o"; done) "${MU300_SYSROOT:-}"
    for _r; do
        # the engine the running service recorded (module v2's /run/mu300-vpn/engine: sing-box for a VLESS xray profile
        # behind the kill switch; the service writes it when it starts the tunnel, mu300-vpn off removes it)
        case $(head -n1 "$_r/run/mu300-vpn/engine" 2>/dev/null) in
            xray) [ "$_x" != vpn-xray ] || return 0 ;; sing-box) [ "$_x" != vpn-singbox ] || return 0 ;;
            mihomo) [ "$_x" != vpn-mihomo ] || return 0 ;; dae) [ "$_x" != vpn-dae ] || return 0 ;;
        esac
        extra_vpn_wanted "$_r" || continue
        _a=$(head -n1 "$_r/etc/mu300/vpn/active" 2>/dev/null | tr -cd 'a-z0-9-')
        if [ -n "$_a" ] && [ -r "$_r/etc/mu300/vpn/profiles/$_a/meta" ]; then
            _t=$(vpn_conf_value "$_r/etc/mu300/vpn/profiles/$_a/meta" TYPE)
            [ "$(vpn_type_engine "$_t")" = "$_x" ] && return 0
            # an xray profile runs on sing-box only with a VLESS link behind the kill switch (as mu300-vpn's
            # engine_in_use); without sing-box it runs on xray, so otherwise vpn-singbox is free to go
            if [ "$_t" = xray ] && [ "$_x" = vpn-singbox ] && vpn_killswitch_wanted "$_r"; then
                case $(head -c 8 "$_r/etc/mu300/vpn/profiles/$_a/uri" 2>/dev/null) in vless://) return 0 ;; esac
            fi
        elif [ ! -d "$_r/etc/mu300/vpn/profiles" ]; then
            # a vpn.conf never migrated: its link runs on xray or sing-box
            case $_x in vpn-xray|vpn-singbox) grep -q '^VLESS_URI=' "$_r/etc/mu300/vpn.conf" 2>/dev/null && return 0 ;; esac
        fi
    done
    return 1
}

# ---- the module as a set -----------------------------------------------------------------------------------------
# vpn_module_get STAGEDIR [FROM]: before anything is changed, the VPN module the device will have: VPN_SET gets
# "NAME FILE SHA" lines for modules_install, the engine extras first and the core (vpn) last; every file checked and
# all from one source - FROM (a directory, or a file whose directory has the engines), or the download. An engine
# the device runs on now (vpn_engine_have) that is not to be had, while the core would replace the vpn extra that
# carries it, makes the set the bundle instead (the core with xray and sing-box), and when there is no bundle either,
# nothing (status 4): an update must never leave a profile without the engine it had. An engine that is installed on
# its own and is not to be had stays as it is; one a profile wants and that was never there is said and skipped.
# Status: 0 (VPN_SET may be empty: everything is up to date), 1 the core is not to be had, 2 a file failed its
# check, 4 an engine is missing (above).
VPN_SET=
vpn_module_get() {
    VPN_SET=
    _vs=$1; _vf=${2:-}
    _ef=$_vf; [ -z "$_vf" ] || [ -d "$_vf" ] || _ef=$(dirname "$_vf")
    module_get vpn "$_vs" "$_vf"; _vr=$?
    case $_vr in 0|3) ;; *) return "$_vr" ;; esac
    _core=; [ "$_vr" = 3 ] || _core="vpn $MODULE_FILE $MODULE_SHA"
    _bundle=$MODULE_BUNDLE
    _set=; _missing=
    for _x in $(vpn_engines_wanted); do
        if [ -n "$_bundle" ]; then case $_x in vpn-xray|vpn-singbox) continue ;; esac; fi
        _xr=0; module_get "$_x" "$_vs" "$_ef" || _xr=$?
        case $_xr in
            0) _set="$_set$_x $MODULE_FILE $MODULE_SHA
" ;;
            3) ;;
            *) if [ -d "$EXTRA/$_x/bin" ]; then
                   echo "extra $_x: not to be had; the installed one ($(extra_release "$_x")) stays" >&2
               elif vpn_engine_have "$_x"; then
                   _missing="$_missing $_x"
               else
                   echo "extra $_x: a profile runs on it and it is not to be had; install it later (mu300-extra install $_x)" >&2
               fi ;;
        esac
    done
    if [ -n "$_missing" ]; then
        # the bundle carries xray and sing-box: the set it makes needs no engine extra for them
        _br=0; module_get vpn-bundle "$_vs" "$_ef" 2>/dev/null || _br=$?
        if { [ "$_br" = 0 ] || [ "$_br" = 3 ]; } && [ -n "$MODULE_BUNDLE" ]; then
            echo "the VPN module's engines$_missing are not to be had: taking mu300-linux-vpn.tar.gz (the core with xray and sing-box) instead" >&2
            VPN_SET=$(printf '%s' "$_set" | grep -v -e '^vpn-xray ' -e '^vpn-singbox ' || true)
            [ "$_br" = 3 ] || VPN_SET="${VPN_SET:+$VPN_SET
}vpn $MODULE_FILE $MODULE_SHA"
            return 0
        fi
        echo "the VPN module needs its engines$_missing, which the device runs on now, and they are not to be had" >&2
        return 4
    fi
    VPN_SET="$_set$_core"
    return 0
}

# module_hook NAME link|unlink SYSROOT: the module's hook for one system (SYSROOT "" is the running one, $DISK/<os>
# another). Run with sh: the disk may be mounted noexec. MU300_DISK and MU300_EXTRA_DIR tell it where it is.
module_hook() {
    [ -f "$EXTRA/$1/hooks/$2" ] || return 0
    MU300_DISK=$DISK MU300_EXTRA_DIR=$EXTRA/$1 sh "$EXTRA/$1/hooks/$2" "$3" ||
        { echo "extra $1: hooks/$2 failed for ${3:-this system}" >&2; return 1; }
}
# module_hook_fits NAME link|unlink SYSROOT VERSION: link only a system the module works with (./requires); an older
# one keeps what its image has (its own mu300-vpn finds the engines in the extra)
module_hook_fits() {
    if [ "$2" = link ] && ! version_ok "$(module_needs "$EXTRA/$1")" "$4"; then
        echo "extra $1: ${3:-this system} is $4, the module needs mu300-linux $(module_needs "$EXTRA/$1"): not linked there" >&2
        return 0
    fi
    module_hook "$1" "$2" "$3"
}
# module_hook_all NAME link|unlink: every installed system; the running one as MU300_SYSROOT ("" on the device)
module_hook_all() {
    _rc=0
    for _o in $(installed_systems); do
        if [ "${MU300_ROOT:-/}" -ef "$DISK/$_o" ]; then _r=${MU300_SYSROOT:-}; else _r=$DISK/$_o; fi
        module_hook_fits "$1" "$2" "$_r" "$(cat "$DISK/$_o$VERSION_FILE" 2>/dev/null || echo unknown)" || _rc=1
    done
    return $_rc
}

# Retire the former optional call-audio module before a system or kernel update. Its
# drivers must not restart with a kernel that no longer reserves their DSP memory.
# Use its own uninstall hook; if it fails, keep its files for an explicit retry.
retire_call_audio() {
    [ -d "$EXTRA/audio" ] || return 0
    [ -f "$EXTRA/audio/hooks/unlink" ] || {
        echo "cannot remove legacy call audio: hooks/unlink is missing; uninstall it before updating" >&2
        return 1
    }
    module_hook_all audio unlink && module_hook audio unlink "${MU300_SYSROOT:-}" || return 1
    rm -rf "$EXTRA/audio" "$EXTRA/.audio.new" "$EXTRA/.audio.old" "$EXTRA/.audio.sha256" "$EXTRA/.audio-firmware"
}

# vpn_in_use "OS...": must the device have the VPN module after an update of OS...? A vpn extra is installed (the
# module, or the engines alone of an older release), mu300-vpn of the running system says it is enabled, or a system
# being updated has ENABLE=1.
vpn_in_use() {
    [ -d "$EXTRA/vpn/bin" ] && return 0
    _v=${MU300_VPN_CMD:-${MU300_BIN:-/opt/mu300/bin}/mu300-vpn}
    [ -x "$_v" ] && [ "$("$_v" enabled </dev/null 2>/dev/null)" = 1 ] && return 0
    for _o in $1; do extra_vpn_wanted "$DISK/$_o" && return 0; done
    return 1
}
vpn_stage_hint() {
    _eng=$(vpn_engines_wanted | sed 's/^vpn-//' | tr '\n' ' ')
    printf '\nCopy SHA256SUMS and mu300-linux-vpn-core.tar.gz with the engines this device needs (%s:\n' "${_eng% }" >&2
    printf 'mu300-linux-vpn-ENGINE.tar.gz each) - or mu300-linux-vpn.tar.gz, the core with xray and sing-box - from\n' >&2
    printf 'https://github.com/%s/releases/latest into %s/ on this device\n' "$VPN_REPO" "$VPN_STAGED" >&2
    printf '(or: MU300_VPN_MODULE=/path/to/that/directory mu300-update apply), or get the device online, and run\n' >&2
    printf 'mu300-update apply again.\n' >&2
}

# extras_to_fetch TAG: the extras of the mu300-linux release an update to TAG downloads - the installed ones that are
# not TAG's (the VPN module comes from its own repository: modules_fetch)
extras_to_fetch() {
    _want=
    for _x in $(extra_installed); do
        extra_known "$_x" && ! extra_is_module "$_x" || continue
        [ "$(extra_release "$_x")" = "$1" ] || _want="$_want $_x"
    done
    echo $_want
}

# modules_fetch TAG "OS...": before anything is changed, the VPN module the device will have after the update (the core
# and the engines, vpn_module_get): MODULES_NEW gets its "NAME FILE SHA" lines for modules_install. MU300_VPN_MODULE
# (a file or a directory), else the copies in VPN_STAGED, else the download. When the VPN is in use, the update
# replaces a system and there is no module, it stops here: the new systems have no mu300-vpn, and a VPN with its kill
# switch would leave the device with no connection after the reboot. An installed module whose set cannot be had
# stays as it is, engines and all.
MODULES_NEW=
modules_fetch() {
    MODULES_NEW=
    _from=${MU300_VPN_MODULE:-}
    if [ -z "$_from" ] && { [ -s "$VPN_STAGED/$(module_asset vpn)" ] || [ -s "$VPN_STAGED/$(module_asset vpn-bundle)" ]; }; then
        _from=$VPN_STAGED
    fi
    if ! vpn_in_use "$2"; then
        # engines without the core (it was removed): each follows its latest release, never fatal
        _ef=$_from; [ -z "$_from" ] || [ -d "$_from" ] || _ef=$(dirname "$_from")
        for _x in $VPN_ENGINE_EXTRAS; do
            [ -d "$EXTRA/$_x/bin" ] || continue
            _r=0; module_get "$_x" "$STAGE/module" "$_ef" || _r=$?
            case $_r in
                0) MODULES_NEW="$MODULES_NEW$_x $MODULE_FILE $MODULE_SHA
" ;;
                3) ;;
                *) echo "extra $_x: not updated; the installed one ($(extra_release "$_x")) stays" >&2 ;;
            esac
        done
        return 0
    fi
    _r=0; vpn_module_get "$STAGE/module" "$_from" || _r=$?
    case $_r in
        0) MODULES_NEW=$VPN_SET ;;
        *) if vpn_module_in "$EXTRA/vpn"; then
               echo "extra vpn: the VPN module could not be updated; the installed one ($(extra_release vpn)) stays, with its engines" >&2
           elif [ -n "$2" ]; then
               vpn_stage_hint
               die "this device uses the VPN, whose toolkit (mu300-vpn) is a module of its own now that the new systems do not carry, and it could not be had: nothing was changed"
           else
               echo "extra vpn: the VPN module could not be had; once the device is online: mu300-extra install vpn" >&2
           fi ;;
    esac
    return 0
}
# modules_install TAG: install what modules_fetch got, before the systems are switched, the engines first and the core
# last: a core is never put in place without the engines its set came with. One that fails its checks (./requires newer
# than TAG, a broken tarball) stops a device that needs it while nothing is changed. The running system keeps working
# meanwhile: its own mu300-vpn finds the engines where they were (a running engine keeps its open files).
modules_install() {
    # own names: module_install -> extra_unpack counts files in _n and _f, which named the module here ("extra 4")
    _mi_bad=
    while read -r _mi_name _mi_file _mi_sha; do
        [ -n "$_mi_name" ] || continue
        if [ "$_mi_name" = vpn ] && [ -n "$_mi_bad" ]; then
            if vpn_module_in "$EXTRA/vpn"; then
                echo "extra vpn: not updated, because its engine$_mi_bad could not be installed; the installed one ($(extra_release vpn)) stays" >&2
                continue
            fi
            vpn_stage_hint
            die "the VPN module's engine$_mi_bad could not be installed (see above): nothing was changed"
        fi
        if module_install "$_mi_name" "$_mi_file" "$_mi_sha" "$1"; then
            printf 'extra %s: %s\n' "$_mi_name" "$(extra_release "$_mi_name")"
            EXTRA_CHANGED=1
        elif [ "$_mi_name" = vpn ] && ! vpn_module_in "$EXTRA/vpn"; then
            vpn_stage_hint
            die "the VPN module could not be installed (see above): nothing was changed"
        else
            echo "extra $_mi_name: not updated (see above)" >&2
            # an engine the core of this set needs, which the device has not got otherwise
            [ "$_mi_name" = vpn ] || vpn_engine_have "$_mi_name" || _mi_bad="$_mi_bad $_mi_name"
        fi
    done <<EOF
$MODULES_NEW
EOF
}
# modules_link "OS...": the updated systems use the module (their images have no mu300-vpn); one the hook could not
# link gets another try at its first boot (mu300-extra link)
modules_link() {
    for _x in vpn $VPN_ENGINE_EXTRAS; do
        [ -f "$EXTRA/$_x/hooks/link" ] || continue
        for _o in $1; do
            module_hook_fits "$_x" link "$DISK/$_o" "$(cat "$DISK/$_o$VERSION_FILE" 2>/dev/null || echo unknown)" ||
                echo "extra $_x: $_o gets it at its first boot instead (mu300-extra link)" >&2
        done
    done
    for _o in $1; do
        extra_vpn_wanted "$DISK/$_o" || continue
        [ ! -e "$DISK/$_o/opt/mu300/bin/mu300-vpn" ] && [ ! -L "$DISK/$_o/opt/mu300/bin/mu300-vpn" ] || continue
        if vpn_killswitch_wanted "$DISK/$_o"; then
            # the systems are switched already: the system itself fails closed (mobile-data and wifi-client keep
            # their uplinks down while its kill switch has no VPN behind it, lib/vpn-orphan.sh) until it is linked
            printf '\n!!! WARNING: %s has the VPN on with its kill switch and no mu300-vpn: mobile data and the Wi-Fi client\n' "$_o" >&2
            printf '!!! stay DOWN there until the module is linked (its first boot tries: mu300-extra link; else\n' >&2
            printf '!!! mu300-extra install vpn on it, or ENABLE=0 in its /etc/mu300/vpn.conf)\n' >&2
        else
            echo "WARNING: $_o uses the VPN and has no mu300-vpn yet: its first boot links it (mu300-extra link), else run mu300-extra install vpn there" >&2
        fi
    done
    return 0
}

# extras_install TAG "NAMES": after the systems are in place, the extras of the release downloaded into $STAGE
extras_install() {
    for _x in $2; do
        if extra_unpack "$_x" "$STAGE/$(extra_asset "$_x")"; then
            printf 'extra %s: %s\n' "$_x" "$1"
            EXTRA_CHANGED=1
        else
            echo "extra $_x: not updated (see above)" >&2
        fi
        rm -f "$STAGE/$(extra_asset "$_x")"
    done
    return 0
}

# panel_configure "OS...": the panel's files in the updated Ubuntu systems that use it (the user's, carried: Cockpit's
# listen drop-in of an older panel bound the socket to br-lan, which held every boot up 90 s), written by the extra's
# own mu300-panel (configure: files only), so the first boot already listens as this release's panel says. That
# boot's mu300-extra link does the same again; a panel extra that cannot (an older one) leaves it to that.
panel_configure() {
    [ -f "$EXTRA/panel/bin/mu300-panel" ] || return 0
    for _o in $1; do
        [ -f "$DISK/$_o/etc/systemd/system/cockpit.socket.d/mu300-listen.conf" ] || continue
        MU300_LIB= MU300_SYSROOT=$DISK/$_o sh "$EXTRA/panel/bin/mu300-panel" configure >/dev/null 2>&1 || true
    done
    return 0
}

# ---- the kernel and the boot image ------------------------------------------------------------------------------
# The boot image in the Linux slot's boot partition (boot_b, or boot_a when Android runs from b) is the stock header
# and AVB tail of this device, the kernel, and a ramdisk that holds this device's own Android files next to the
# generic part (init, busybox, modules). The kernel unpacks concatenated ramdisk segments in turn and a later file
# replaces an earlier one, so an update keeps the device's ramdisk as it is and appends the release's generic segment
# (ramdisk-generic.lz4 in mu300-kernel.tar.gz): nothing has to be unpacked or compressed here, and nothing from
# Android is needed. The device's segment is kept in $BOOTDIR, so the image does not grow with every update; it is
# taken from the partition again whenever it was not written by us (a new install from a computer).
BOOTDIR=$DISK/boot
PERSIST_LOG=$((48 << 20))   # the boot partition keeps the persistent init log from 48 MiB on (boot/build-boot-image.py)

# Which kernel this device runs: the vendor 5.4 (mu300-kernel.tar.gz) or a mainline one (mu300-kernel-<version>.tar.gz:
# 6.18, the long-term release, and 7.3, the stable one).
# Kept on the Linux partition, so both systems and every update follow it - without it an update of a device on
# 6.18 installed the release's 5.4 kernel. "mu300-update kernel 6.18" changes it.
KERNEL_CHOICE=$BOOTDIR/kernel
KERNELS="5.4 6.18 7.3"
# A series kernel.org has ended, and the one that takes its place: the releases no longer carry its bundle, so a device
# that chose it gets the next one with its next update, through the same boot update as any other (the image in the
# slot is kept for rollback-boot, and a kernel that does not start falls back to Android by itself). Never 5.4 instead:
# an unknown choice means 5.4, and Ubuntu 26.04 does not run there. 7.2 ended with 7.2.15 (2026-11).
KERNELS_RETIRED="7.2:7.3"
kernel_retired() {  # kernel_retired VERSION: the kernel that takes its place when VERSION is retired; else status 1
    for _kr in $KERNELS_RETIRED; do [ "${_kr%%:*}" = "$1" ] && { echo "${_kr#*:}"; return 0; }; done
    return 1
}
kernel_chosen() { cat "$KERNEL_CHOICE" 2>/dev/null; }   # what is written down, which may be a retired kernel
kernel_choice() { c=$(kernel_chosen); case " $KERNELS " in *" $c "*) echo "$c" ;; *) kernel_retired "$c" || echo 5.4 ;; esac; }
# kernel_retired_note: a line saying that the kernel this device chose is retired and what it gets instead (once a run)
KERNEL_RETIRED_SAID=
kernel_retired_note() {
    [ -z "$KERNEL_RETIRED_SAID" ] || return 0
    _kc=$(kernel_chosen); _kn=$(kernel_retired "$_kc") || return 0
    KERNEL_RETIRED_SAID=1
    printf 'kernel: %s is retired (kernel.org ended that series) and releases no longer carry it; this device moves to %s, the\n' "$_kc" "$_kn"
    printf '        kernel that takes its place. The image in the slot now is kept: mu300-update rollback-boot goes back to it.\n'
}
# kernel_choice_settle [KERNEL.RELEASE]: once the image of the kernel that took a retired one's place is written, that
# kernel is the choice written down (the note is not said again). Not when the image holds another kernel (a local
# MU300_KERNEL_BUNDLE): the choice then stays as it was.
kernel_choice_settle() {
    _kc=$(kernel_chosen); _kn=$(kernel_retired "$_kc") || return 0
    _kv=$(cat "${1:-/nonexistent}" 2>/dev/null)
    case $_kv in ''|"$_kn".*) ;; *) return 0 ;; esac
    echo "$_kn" > "$KERNEL_CHOICE"
    printf 'kernel: the choice is %s now (it was %s)\n' "$_kn" "$_kc"
}
kernel_asset() { case $(kernel_choice) in 5.4) echo mu300-kernel.tar.gz ;; *) echo "mu300-kernel-$(kernel_choice).tar.gz" ;; esac; }

# The slot Linux runs from (Android may be on either): what the initramfs published, else the slot LK booted
# (androidboot.slot_suffix on the command line, or in the bootargs a mainline kernel leaves in the device tree), and
# b only when nothing says - an initramfs from before slot a, which LK can only have booted from b.
linux_slot() {
    _s=$(cat "${MU300_SYSROOT:-}/run/mu300/linux-slot" 2>/dev/null)
    case $_s in a|b) echo "$_s"; return ;; esac
    for _f in "${MU300_SYSROOT:-}/proc/cmdline" "${MU300_SYSROOT:-}/proc/device-tree/chosen/bootargs"; do
        [ -r "$_f" ] || continue
        _s=$(tr '\000' ' ' < "$_f" | sed -n 's/.*androidboot\.slot_suffix=_\([ab]\).*/\1/p')
        [ -n "$_s" ] && { echo "$_s"; return; }
    done
    echo b
}
# The internal disk - the eMMC whatever its number (FINDINGS 31l), or a UFS (issue #396) - and its partitions: a copy
# of lib/storage.sh, which tests/test_storage_lib.py keeps the same. A copy, not the file: a self-update runs this
# script from the new release on a system that may not have that file yet.
# --- storage begin
mu300_storage_mmc() {  # mu300_storage_mmc TYPE: the whole mmcblkN disks whose card is of TYPE (MMC, SD)
    for _mu300sb in "${MU300_SYS:-/sys}"/block/mmcblk*; do
        case ${_mu300sb##*/mmcblk} in ''|*[!0-9]*) continue ;; esac   # not mmcblk0boot0, mmcblk0rpmb, ...
        [ "$(cat "$_mu300sb/device/type" 2>/dev/null)" != "$1" ] || echo "${_mu300sb##*/}"
    done
    return 0
}
mu300_storage_ufs() {  # mu300_storage_ufs DISK: is DISK a disk of the UFS host?
    case ${1##*/} in sd[a-z]|sd[a-z][a-z]) ;; *) return 1 ;; esac
    _mu300sp=$(readlink -f "${MU300_SYS:-/sys}/block/${1##*/}" 2>/dev/null) || return 1
    case $_mu300sp in */*.ufs/host[0-9]*/*) return 0 ;; esac
    return 1
}
mu300_storage_prefix() {  # mu300_storage_prefix DISK: what its partitions' names are DISK plus a number after
    case ${1##*/} in *[0-9]) echo "${1##*/}p" ;; *) echo "${1##*/}" ;; esac
}
mu300_storage_parts() {  # mu300_storage_parts DISK: the names of its partitions (mmcblk0p1 ..., sda1 ...)
    _mu300sx=$(mu300_storage_prefix "$1")
    for _mu300sq in "${MU300_SYS:-/sys}/block/${1##*/}/$_mu300sx"[0-9]*; do
        [ -d "$_mu300sq" ] && echo "${_mu300sq##*/}"
    done
    return 0
}
mu300_storage_part() {  # mu300_storage_part NAME [DISK]: the partition named NAME in the GPT of DISK (internal)
    _mu300sd=${2:-}
    [ -n "$_mu300sd" ] || _mu300sd=$(mu300_storage_disk) || return 1
    for _mu300sq in $(mu300_storage_parts "$_mu300sd"); do
        grep -qx "PARTNAME=$1" "${MU300_SYS:-/sys}/block/${_mu300sd##*/}/$_mu300sq/uevent" 2>/dev/null || continue
        echo "$_mu300sq"
        return 0
    done
    return 1
}
mu300_storage_disk() {  # mu300_storage_disk: the internal disk's name; status 1 when it is not there (yet)
    for _mu300sd in $(mu300_storage_mmc MMC); do echo "$_mu300sd"; return 0; done
    for _mu300sb in "${MU300_SYS:-/sys}"/block/sd*; do
        mu300_storage_ufs "$_mu300sb" && mu300_storage_part misc "${_mu300sb##*/}" >/dev/null &&
            { echo "${_mu300sb##*/}"; return 0; }
    done
    for _mu300sb in "${MU300_SYS:-/sys}"/block/mmcblk*; do
        case ${_mu300sb##*/mmcblk} in ''|*[!0-9]*) continue ;; esac
        [ "$(cat "$_mu300sb/device/type" 2>/dev/null)" = SD ] || { echo "${_mu300sb##*/}"; return 0; }
    done
    return 1
}
mu300_storage_sector_size() {  # mu300_storage_sector_size DISK: its logical block size, 512 or 4096
    _mu300ss=$(cat "${MU300_SYS:-/sys}/block/${1##*/}/queue/logical_block_size" 2>/dev/null) || _mu300ss=
    case $_mu300ss in 4096) echo 4096 ;; *) echo 512 ;; esac
}
# --- storage end
# The partition named NAME on the internal disk. Never a card's - one can carry the same GPT names (a raw clone of a
# device backup), and the kernel is written to what this finds.
part_dev() {  # part_dev NAME -> /dev/<block device of that partition>; status 1 when the internal disk has none
    _pn=$(MU300_SYS=${MU300_SYSROOT:-}/sys; mu300_storage_part "$1") || return 1
    echo "/dev/$_pn"
}
# boot_dev NAME: part_dev, and only a block device. On OpenWrt the early recorder once wrote its log while procd put
# a new /dev in place, and so made /dev/<boot partition> a plain file in RAM (U30 Air, FINDINGS 86): a boot image
# written there reads back as written, and the device would boot the old one under the new one's name.
boot_dev() {
    _bd=$(part_dev "$1") || { echo "no $1 partition found" >&2; return 1; }
    [ -b "$_bd" ] || { echo "$_bd is not a block device (a reboot makes /dev anew): $1 was not touched" >&2; return 1; }
    echo "$_bd"
}
u32() { od -An -tu4 -j "$2" -N4 "$1" | tr -d ' \n'; }                 # u32 FILE OFFSET (little endian)
be64() { printf '%d' "0x$(od -An -tx1 -j "$2" -N8 "$1" | tr -d ' \n')"; }  # be64 FILE OFFSET
bytes() {  # bytes VALUE COUNT le|be: the value as raw bytes
    v=$1 n=$2 i=0
    while [ "$i" -lt "$n" ]; do
        if [ "$3" = le ]; then s=$((8 * i)); else s=$((8 * (n - 1 - i))); fi
        printf "\\$(printf %o $(( (v >> s) & 255 )))"
        i=$((i + 1))
    done
}
poke() { dd of="$1" bs=1 seek="$2" conv=notrunc 2>/dev/null; }      # poke FILE OFFSET < bytes
fsize() { wc -c < "$1" | tr -d ' '; }
pad_page() { p=$(( (4096 - $(fsize "$1") % 4096) % 4096 )); [ "$p" = 0 ] || head -c "$p" /dev/zero >> "$1"; }
head_sha() { dd if="$1" bs=4096 count=$(( ($2 + 4095) / 4096 )) 2>/dev/null | head -c "$2" | sha256sum | cut -d' ' -f1; }

# write BODY (from offset 0), VBMETA right behind it and FOOTER into the last 64 bytes of the boot partition, then
# read it back
# BODY is whole pages (bootimg_assemble pads it, a kept image is read in pages): VBMETA is written behind it by a second
# dd, not from a copy of the two joined - that copy was one more image's worth of room on the Linux partition during
# a kernel update (docs/FINDINGS.md 177). A body that is not whole pages is joined as before.
write_boot() {  # write_boot DEV PSIZE BODY VBMETA FOOTER
    _wb=$(fsize "$3")
    if [ $((_wb % 4096)) = 0 ]; then
        dd if="$3" of="$1" bs=4096 conv=notrunc 2>/dev/null &&
            dd if="$4" of="$1" bs=4096 seek=$((_wb / 4096)) conv=notrunc 2>/dev/null && sync || return 1
    else
        cat "$3" "$4" > "$3.all" && dd if="$3.all" of="$1" bs=4096 conv=notrunc 2>/dev/null && sync ||
            { rm -f "$3.all"; return 1; }
        rm -f "$3.all"
    fi
    dd if="$5" of="$1" bs=64 seek=$(($2 / 64 - 1)) conv=notrunc 2>/dev/null && sync || return 1
    echo 3 > /proc/sys/vm/drop_caches 2>/dev/null
    [ "$(head_sha "$1" $((_wb + $(fsize "$4"))))" = "$(cat "$3" "$4" | sha256sum | cut -d' ' -f1)" ] || return 1
    [ "$(dd if="$1" bs=64 skip=$(($2 / 64 - 1)) count=1 2>/dev/null | sha256sum | cut -d' ' -f1)" = \
      "$(sha256sum < "$5" | cut -d' ' -f1)" ] || return 1
}

part_size() { blockdev --getsize64 "$1" 2>/dev/null || fsize "$1"; }   # part_size DEV: bytes (a file in tests)
part_bytes() { echo $(( $(cat "/sys/class/block/${1##*/}/size") * 512 )); }   # part_bytes DEV: as the kernel lists it

# The part of a new boot image both builders share. DIR/new holds the header page (the caller has set what is its
# own: the command line, the signature size), DIR/footer the footer to copy. This puts the kernel's and the ramdisks'
# sizes into the header, appends kernel and ramdisks page-aligned, refuses a result that would reach the persistent
# init log, and writes DIR/newfooter with the new sizes.
bootimg_assemble() {  # bootimg_assemble DIR VBMETA_SIZE KERNEL RAMDISK...
    _dir=$1 _vs=$2 _kernel=$3; shift 3
    _rsz=0
    for _r in "$@"; do _rsz=$((_rsz + $(fsize "$_r"))); done
    bytes "$(fsize "$_kernel")" 4 le | poke "$_dir/new" 8
    bytes "$_rsz" 4 le | poke "$_dir/new" 12
    _hs=$(fsize "$_dir/new") _ksz=$(fsize "$_kernel")
    cat "$_kernel" >> "$_dir/new"; pad_page "$_dir/new"
    cat "$@" >> "$_dir/new"; pad_page "$_dir/new"
    _os=$(fsize "$_dir/new")
    # the file must be what was just put together: two updaters in the same directory once both appended their
    # kernel to it, and the size check below then refused a 56 MB "image" (lock_take keeps them apart now)
    [ "$_os" = $(( (_hs + _ksz + 4095) / 4096 * 4096 + (_rsz + 4095) / 4096 * 4096 )) ] ||
        { echo "boot: $_dir/new is not the image just assembled ($_os bytes; another mu300-update in the same directory?)" >&2; return 1; }
    [ $((_os + _vs)) -le "$PERSIST_LOG" ] ||
        { echo "boot: the new image ($_os bytes: kernel $_ksz, ramdisks $_rsz, with vbmeta $_vs) would reach the persistent log area at $PERSIST_LOG bytes" >&2; return 1; }
    cp "$_dir/footer" "$_dir/newfooter"
    { bytes "$_os" 8 be; bytes "$_os" 8 be; bytes "$_vs" 8 be; } | poke "$_dir/newfooter" 12
}

# A boot image for the Linux slot made from Android's own (STOCK, a partition or a file): the Magisk installer has
# no image of ours to start from, only Android's. Its header page with this kernel's and ramdisk's sizes, the
# command line loglevel=5 and no signature; its vbmeta and its AVB footer with the new sizes. The same bytes
# boot/build-boot-image.py makes on a computer (tests/test_update.py compares them). Writes DIR/new, DIR/vbmeta and
# DIR/newfooter, which write_boot takes.
bootimg_from_stock() {  # bootimg_from_stock STOCK KERNEL RAMDISK DIR
    _ps=$(part_size "$1") || return 1
    dd if="$1" of="$4/hdr" bs=4096 count=1 2>/dev/null
    dd if="$1" of="$4/footer" bs=64 skip=$((_ps / 64 - 1)) count=1 2>/dev/null
    [ "$(head -c 8 "$4/hdr")" = ANDROID! ] && [ "$(u32 "$4/hdr" 40)" = 4 ] ||
        { echo "boot: $1 does not hold a boot image header v4" >&2; return 1; }
    [ "$(head -c 4 "$4/footer")" = AVBf ] || { echo "boot: $1 has no AVB footer" >&2; return 1; }
    _vo=$(be64 "$4/footer" 20); _vs=$(be64 "$4/footer" 28)
    # vbmeta need not start on a page: read the pages that hold it and cut it out
    dd if="$1" bs=4096 skip=$((_vo / 4096)) count=$(( (_vo % 4096 + _vs + 4095) / 4096 )) 2>/dev/null |
        tail -c +$((_vo % 4096 + 1)) | head -c "$_vs" > "$4/vbmeta"
    [ "$(fsize "$4/vbmeta")" = "$_vs" ] || { echo "boot: cannot read the vbmeta of $1" >&2; return 1; }
    cp "$4/hdr" "$4/new"
    { printf 'loglevel=5'; head -c 1526 /dev/zero; } | poke "$4/new" 44
    bytes 0 4 le | poke "$4/new" 1580
    bootimg_assemble "$4" "$_vs" "$2" "$3" || return 1
    rm -f "$4/hdr" "$4/footer"
}

# A kernel the systems were not built with (a mainline bundle) brings its modules along: they go into every system
# on the Linux filesystem, next to the ones of the other kernel, which stay for a switch back. Ubuntu keeps them under
# extra/ and indexes them (depmod; MU300_NO_DEPMOD=1 leaves that to its next boot, as the Magisk installer must: the
# depmod Android has is busybox's); OpenWrt keeps them flat and loads by path.
# modules_dir OS KREL: where the modules of a kernel bundle go in OS
modules_dir() { case $1 in ubuntu) echo "$DISK/$1/lib/modules/$2/extra" ;; *) echo "$DISK/$1/lib/modules/$2" ;; esac; }

# The set a bundle replaces belongs to the boot image it replaces: two builds of one kernel release (6.18.55 of two
# releases) share the directory, and a kernel with the other build's modules does not come up (the one-boot fallback
# takes the device back to Android). So the set in place is kept with the previous image, and goes back with it -
# in rollback-boot, and when writing the new image fails.
#
# Room (docs/FINDINGS.md 177): since every module is built (FINDINGS 163) a set is some 2950 files, 120 MB,
# and copies of it - kept beside the new set, put into each system - made a kernel update want 500 MB free at once,
# more than F50-C's 804 MiB region had. Sets are never copied now: the kept set, the sets in the systems and the
# unpacked bundle are all on the Linux partition, so a set is given more names (ln) and a name is removed, never a
# file written into (the delta block's second names, see kernel_modules_into_systems). cp only where a link cannot be
# made (another filesystem: a bundle unpacked elsewhere by an installer).
# mod_link FROM TO: the *.ko of FROM into TO (where none of those names is), as second names
mod_link() {
    ls "$1"/*.ko >/dev/null 2>&1 || return 0
    ln "$1"/*.ko "$2/" 2>/dev/null && return 0
    rm -f "$2"/*.ko
    cp "$1"/*.ko "$2/"
}
# prev_modules_save BUNDLE_DIR (unpacked; a bundle without kernel.release keeps nothing): the set in place now of the
# bundle's release, into prev.modules.new; the kept set of the image before it (prev.modules) stays until the new one
# is taken (prev_modules_commit), so an update that stops before its image is written leaves both as they were
prev_modules_save() {
    _pm=$BOOTDIR/prev.modules.new
    rm -rf "$_pm"
    _krel=$(cat "$1/kernel.release" 2>/dev/null) || return 0
    case $_krel in ''|*/*|.*) return 0 ;; esac
    mkdir -p "$_pm" && echo "$_krel" > "$_pm/kernel.release" || return 1
    for _os in $(installed_systems); do
        _d=$(modules_dir "$_os" "$_krel")
        ls "$_d"/*.ko >/dev/null 2>&1 || continue
        mkdir -p "$_pm/$_os" && mod_link "$_d" "$_pm/$_os" || { rm -rf "$_pm"; return 1; }
    done
}
# prev_modules_commit: the set prev_modules_save kept becomes the one of the previous image (with prev.body)
prev_modules_commit() {
    rm -rf "$BOOTDIR/prev.modules"
    [ ! -d "$BOOTDIR/prev.modules.new" ] || mv "$BOOTDIR/prev.modules.new" "$BOOTDIR/prev.modules"
}
# prev_modules_restore [DIR]: the kept set (DIR: prev.modules) back into the systems; it stays kept
prev_modules_restore() {
    _pm=${1:-$BOOTDIR/prev.modules}
    _krel=$(cat "$_pm/kernel.release" 2>/dev/null) || return 0
    case $_krel in ''|*/*|.*) return 0 ;; esac
    for _os in $(installed_systems); do
        _d=$(modules_dir "$_os" "$_krel")
        [ -d "$_d" ] || continue
        rm -f "$_d"/*.ko
        # a system that had no set of this release then gets none now (the kernel back is another release)
        [ -d "$_pm/$_os" ] || continue
        mod_link "$_pm/$_os" "$_d" || { echo "boot: the previous modules of $_os did not go back" >&2; return 1; }
        if [ "$_os" = ubuntu ] && [ -z "${MU300_NO_DEPMOD:-}" ] && command -v depmod >/dev/null; then
            depmod -b "$DISK/$_os" "$_krel" 2>/dev/null || true
        fi
    done
    printf 'boot: the modules of the previous image (%s) are back in: %s\n' "$_krel" "$(installed_systems)"
}

kernel_modules_into_systems() {  # kernel_modules_into_systems BUNDLE_DIR (unpacked)
    _krel=$(cat "$1/kernel.release" 2>/dev/null)
    case $_krel in ''|*/*|.*) echo "boot: bad kernel release '$_krel' in the bundle" >&2; return 1 ;; esac
    for _os in $(installed_systems); do
        _d=$(modules_dir "$_os" "$_krel")
        # the set of the bundle replaces the one of an earlier bundle of this release: a module it no longer has
        # would otherwise stay loadable. Removed, then linked: never written into (the delta block)
        mkdir -p "$_d" && rm -f "$_d"/*.ko && mod_link "$1/modules" "$_d" ||
            { echo "boot: installing the modules into $_os failed" >&2; return 1; }
        if [ "$_os" = ubuntu ]; then
            # what the kernel has built in (bundles from v2026.09.29 on): modprobe of a built-in driver then
            # succeeds, and depmod stops warning (removed first, never written into: the image's file may be a
            # second name of the previous version's, the delta block)
            for _f in modules.builtin modules.builtin.modinfo; do [ ! -f "$1/$_f" ] || { rm -f "$DISK/$_os/lib/modules/$_krel/$_f"; cp "$1/$_f" "$DISK/$_os/lib/modules/$_krel/"; }; done
            [ -e "$DISK/$_os/lib/modules/$_krel/modules.order" ] || : > "$DISK/$_os/lib/modules/$_krel/modules.order"
            if [ -z "${MU300_NO_DEPMOD:-}" ] && command -v depmod >/dev/null; then depmod -b "$DISK/$_os" "$_krel" 2>/dev/null || true; fi
        fi
    done
    printf 'boot: %s modules for %s installed into: %s\n' "$(ls "$1/modules" | wc -l | tr -d ' ')" "$_krel" "$(installed_systems)"
}

# The room the kernel step takes on the Linux partition (docs/FINDINGS.md 177): the bundle (20 to 55 MB) until it is
# unpacked, what is unpacked from it (a mainline bundle: some 150 MB, 120 MB of it modules, that stay as the systems'
# set), and the image in the slot now beside the new one (kept as prev.body, 25 to 30 MB each). The bundle is removed
# once unpacked, so the peak is what is unpacked and the larger of the bundle and the two images.
BOOT_IMAGES_KB=65536    # two boot images, before the one in the slot is read
# kernel_need_kb TAG: the KiB free the kernel step wants before its bundle is downloaded (unpacked: three times the
# bundle; the release's are 2.4 to 2.9). A bundle in $STAGE already takes its room: only what it adds is counted.
kernel_need_kb() {
    _ka=$(kernel_asset)
    if [ -s "$STAGE/$_ka" ]; then
        _kd=$(( $(fsize "$STAGE/$_ka") / 1024 + 1 ))
        _ki=$(( BOOT_IMAGES_KB > _kd ? BOOT_IMAGES_KB - _kd : 0 ))
    else
        _kd=$(asset_kb "$1" "$_ka") || _kd=65536
        _ki=$(( BOOT_IMAGES_KB > _kd ? BOOT_IMAGES_KB : _kd ))
    fi
    echo $(( 3 * _kd + _ki + 16384 ))
}
# What the room is spent on between updates (docs/FINDINGS.md 177), and what of it an update may take back:
#   * the boot image kept for rollback-boot - the one before the image in place - with its set of modules (120 MB of
#     files of its own once a kernel update has replaced that set). An update replaces both anyway once it has
#     written its image, and the device runs the image in place either way, so when the room is short they are given
#     up first, together (rollback-boot then says none is kept; it never puts back an image without its modules).
#   * module sets of kernels no boot image here runs: each kernel release a bundle brought left its set behind (6.18.56
#     beside 6.18.57 on F50-C), 120 MB each since every module is built. A set is needed by the image in the slot, the
#     kept image and the running kernel only - a switch to another kernel brings its own set - so the others go.
#     Sets of the vendor kernel (5.4.*) are the systems' own and never touched, and so is a directory without modules.
# image_krel IMAGE: the release of the kernel in a boot image (a partition, or a kept image): its banner
image_krel() {
    _iz=$(u32 "$1" 8)
    case $_iz in ''|0|*[!0-9]*) return 1 ;; esac
    dd if="$1" bs=4096 skip=1 count=$(( (_iz + 4095) / 4096 )) 2>/dev/null |
        grep -a -o -m 1 'Linux version [0-9][^ ]*' | cut -d' ' -f3
}
# kernel_set_from_old KREL: a system an update just replaced has no set of a bundle's yet when Ubuntu is updated (its
# lib/modules is never carried over: the sets come from the bundles), so the image in the slot - kept for rollback-boot
# once the new one is written - would come back without its modules. The previous system kept beside it (<os>.old)
# ran with that image: its set is given to the new system (second names, no room). OpenWrt carries its sets.
kernel_set_from_old() {
    case $1 in ''|*/*|.*) return 0 ;; esac
    for _os in $(installed_systems); do
        _d=$(modules_dir "$_os" "$1"); _o=$DISK/$_os.old/${_d#"$DISK/$_os/"}
        ! ls "$_d"/*.ko >/dev/null 2>&1 && ls "$_o"/*.ko >/dev/null 2>&1 || continue
        mkdir -p "$_d" && mod_link "$_o" "$_d" || { echo "boot: the modules of $1 did not go from $_os.old into $_os" >&2; continue; }
        if [ "$_os" = ubuntu ]; then
            for _f in modules.builtin modules.builtin.modinfo modules.order; do
                [ ! -f "$DISK/$_os.old/lib/modules/$1/$_f" ] || [ -e "$DISK/$_os/lib/modules/$1/$_f" ] ||
                    cp "$DISK/$_os.old/lib/modules/$1/$_f" "$DISK/$_os/lib/modules/$1/"
            done
            if [ -z "${MU300_NO_DEPMOD:-}" ] && command -v depmod >/dev/null; then depmod -b "$DISK/$_os" "$1" 2>/dev/null || true; fi
        fi
        printf 'boot: the modules of %s (the image in the slot) taken over from %s.old into %s\n' "$1" "$_os" "$_os"
    done
}
# kernel_sets KREL...: the module sets (OS:KREL) in the systems of releases other than these
kernel_sets() {
    _kp=" $* "
    for _os in $(installed_systems); do
        for _kd in "$DISK/$_os"/lib/modules/*; do
            [ -d "$_kd" ] && [ ! -L "$_kd" ] || continue
            _kn=${_kd##*/}
            case $_kn in 5.4.*|.*) continue ;; esac
            case $_kp in *" $_kn "*) continue ;; esac
            ls "$(modules_dir "$_os" "$_kn")"/*.ko >/dev/null 2>&1 && printf '%s:%s\n' "$_os" "$_kn"
        done
    done
}
# kernel_sets_kb OS:KREL...: the KiB removing them frees
kernel_sets_kb() {
    [ $# -gt 0 ] || { echo 0; return; }
    for _ks in "$@"; do echo "$DISK/${_ks%%:*}/lib/modules/${_ks#*:}"; done | xargs du -sk 2>/dev/null |
        awk '{ k += $1 } END { print k + 0 }'
}
kernel_sets_remove() {  # kernel_sets_remove OS:KREL...
    [ $# -gt 0 ] || return 0
    for _ks in "$@"; do rm -rf "${DISK:?}/${_ks%%:*}/lib/modules/${_ks#*:}"; done
    printf 'boot: modules of kernels no boot image here runs removed: %s\n' "$*"
}
# BOOT_SLOT_KREL BOOT_KEPT_KREL: the releases of the image in the slot and of the kept image (boot_update_run reads
# them; empty: not known, and then no set is removed)
BOOT_SLOT_KREL= BOOT_KEPT_KREL=
boot_sets_stale() {  # boot_sets_stale [NEW_KREL]: the sets no image needs, with the kept image's (set 0) or without
    [ -n "$BOOT_SLOT_KREL" ] || return 0
    if [ -s "$BOOTDIR/prev.body" ]; then
        [ -n "$BOOT_KEPT_KREL" ] || return 0
        kernel_sets "$BOOT_SLOT_KREL" "$BOOT_KEPT_KREL" "$(uname -r)" "$@"
    else
        kernel_sets "$BOOT_SLOT_KREL" "$(uname -r)" "$@"
    fi
}
# boot_kept_kb [NEW_KREL]: the KiB giving the kept image up frees: the image, the files of its set that have no other
# name (one a rollback-boot put back into the systems is theirs too), and its release's sets in the systems when no
# other image needs them
boot_kept_kb() {
    _kk=0
    [ ! -f "$BOOTDIR/prev.body" ] || _kk=$(( $(fsize "$BOOTDIR/prev.body") / 1024 ))
    [ ! -d "$BOOTDIR/prev.modules" ] ||
        _kk=$(( _kk + $(ls -lnR "$BOOTDIR/prev.modules" 2>/dev/null | awk '$1 ~ /^-/ && $2 == 1 { k += int(($5 + 4095) / 4096) * 4 } END { print k + 0 }') ))
    if [ -s "$BOOTDIR/prev.body" ] && [ -n "$BOOT_SLOT_KREL" ] && [ -n "$BOOT_KEPT_KREL" ]; then
        _kk=$(( _kk + $(kernel_sets_kb $(kernel_sets "$BOOT_SLOT_KREL" "$(uname -r)" "$@" | grep ":$BOOT_KEPT_KREL\$")) ))
    fi
    echo "$_kk"
}
boot_kept_drop() {  # boot_kept_drop [NEW_KREL]
    printf 'boot: the room is short: the boot image kept from before the one in place (%s) and its modules are given up\n' \
        "$(cat "$BOOTDIR/prev.tag" 2>/dev/null || echo unknown)"
    rm -rf "${BOOTDIR:?}/prev.modules" "$BOOTDIR/prev.body" "$BOOTDIR/prev.vbmeta" "$BOOTDIR/prev.footer" \
        "$BOOTDIR/prev.slot" "$BOOTDIR/prev.tag" "$BOOTDIR/prev.kernel"
    kernel_sets_remove $(boot_sets_stale "$@")
}
# boot_room BUNDLE LIST IMAGES_KB: whether the partition has the KiB unpacking BUNDLE (in place already) and making the
# image want free - its tar stream (the files and their headers), a block's slack for each file, and IMAGES_KB less
# the bundle that is removed once unpacked - giving up the kept image when that makes it; status 1, with the numbers
# said, when it has less
boot_room() {
    _bt=$(gzip -dc < "$1" 2>/dev/null | wc -c | tr -d ' ')
    case $_bt in ''|0|*[!0-9]*) return 0 ;; esac
    _bu=$(( _bt / 1024 + 4 * $(wc -l < "$2") ))
    _bd=$(( $(fsize "$1") / 1024 ))
    _bn=$(( _bu + ($3 > _bd ? $3 - _bd : 0) + 8192 ))
    _bf=$(df -Pk "$DISK" | awk 'NR == 2 { print $4 }')
    [ "${_bf:-0}" -ge "$_bn" ] && return 0
    _br=$(untar -xzOf "$1" ./kernel.release 2>/dev/null)
    _bk=$(boot_kept_kb $_br)
    if [ $(( ${_bf:-0} + _bk )) -ge "$_bn" ]; then boot_kept_drop $_br; return 0; fi
    echo "boot: not enough free space on the Linux partition for the kernel: $((_bn / 1024)) MB needed (the unpacked kernel bundle, $((_bu / 1024)) MB with its modules, and the boot images), $((${_bf:-0} / 1024)) MB free and $((_bk / 1024)) MB in the boot image kept for rollback-boot. Nothing was changed (the download was removed). mu300-update clean deletes the kept previous versions of the systems" >&2
    return 1
}

# A restart in the middle of the kernel step (#422, docs/FINDINGS.md 235): the systems' set of the bundle's release is
# replaced before the image is written, and the two belong together - a module of one build in the kernel of another
# reads the wrong offsets (sprd_wlan_combo's probe: an Oops 25 s into the boot, and the fallback went to Android). And
# what was unpacked last had not reached the disk yet: 307 modules came back as empty files. So the unpacked set is
# checked and on the disk (sync) before any system gets it, and from the moment the systems' set is touched until the
# image is written, $BOOTDIR/modules.pending says so: the release and the banner of the new kernel. Whoever finds it
# next - the ramdisk's init before the system starts (boot/init, modules_settle), or the next mu300-update - puts in
# the set of the image in the slot: the unpacked bundle's when that is the new kernel, else the set kept with the
# image before (prev_modules_restore).
# kernel_banner < KERNEL: the banner /proc/version shows. An Image holds two: the one of init/version.o, whose build
# number and time are left out ("# SMP "), and the one put in at the final link ("#1 SMP Tue Oct 27 ...", seen on
# 6.18.59) - only that one tells two builds of a release apart
kernel_banner() { grep -a -o 'Linux version [0-9][^[:cntrl:]]* #[0-9][^[:cntrl:]]*' | head -n 1; }
image_banner() {  # image_banner IMAGE: the banner of the kernel in a boot image (a partition, or a kept image)
    _iz=$(u32 "$1" 8)
    case $_iz in ''|0|*[!0-9]*) return 1 ;; esac
    dd if="$1" bs=4096 skip=1 count=$(( (_iz + 4095) / 4096 )) 2>/dev/null | kernel_banner
}
# modules_complete BUNDLE_DIR LIST: every module the bundle lists is unpacked, none of them empty
modules_complete() {
    _mn=$(grep -c '^\./modules/[^/]*\.ko$' "$2")
    [ "$(ls "$1/modules" 2>/dev/null | grep -c '\.ko$')" = "$_mn" ] || return 1
    [ "$_mn" = 0 ] && return 0
    for _mf in "$1"/modules/*.ko; do [ -s "$_mf" ] || return 1; done
}
# modules_pending KREL BANNER: written down, and on the disk, before the systems' set changes
modules_pending() {
    printf '%s\n%s\n' "$1" "$2" > "$BOOTDIR/modules.pending.new" &&
        mv -f "$BOOTDIR/modules.pending.new" "$BOOTDIR/modules.pending" && sync
}
modules_done() { rm -f "$BOOTDIR/modules.pending"; sync; }
# modules_settle: the set a kernel step that stopped left in the systems, made the one of the image in the slot
modules_settle() {
    [ -f "$BOOTDIR/modules.pending" ] || return 0
    _sk=$(sed -n 1p "$BOOTDIR/modules.pending"); _sb=$(sed -n 2p "$BOOTDIR/modules.pending")
    case $_sk in ''|*/*|.*) modules_done; return 0 ;; esac
    # (an image whose banner cannot be read is not the new kernel: that one's was read)
    _sd=$(boot_dev "boot_$(linux_slot)" 2>/dev/null) && [ -r "$_sd" ] ||
        { echo "boot: a kernel step stopped half-way and the boot image cannot be read to settle its modules; the next start does" >&2; return 1; }
    _ss=$(image_banner "$_sd")
    if [ -n "$_sb" ] && [ "$_ss" = "$_sb" ]; then
        echo "boot: the last kernel step stopped after writing its image: its modules go in again"
        ls "$STAGE/boot/modules"/*.ko >/dev/null 2>&1 && [ "$(cat "$STAGE/boot/kernel.release" 2>/dev/null)" = "$_sk" ] ||
            { echo "boot: the unpacked modules of that step are gone; run mu300-update boot before restarting" >&2; modules_done; return 1; }
        kernel_modules_into_systems "$STAGE/boot" || return 1
    else
        echo "boot: the last kernel step stopped before writing its image: the modules of the image in place go back"
        for _sp in "$BOOTDIR/prev.modules.new" "$BOOTDIR/prev.modules" ''; do
            [ "$(cat "$_sp/kernel.release" 2>/dev/null)" != "$_sk" ] || break
        done
        if [ -n "$_sp" ]; then
            prev_modules_restore "$_sp" || return 1
        else
            # nothing was kept: the systems had no set of this release
            for _os in $(installed_systems); do rm -f "$(modules_dir "$_os" "$_sk")"/*.ko; done
        fi
    fi
    modules_done
}

# boot_update TAG: the kernel step. However it ends, nothing of it stays on the partition but what it put in place:
# the unpacked bundle and the images being made go, a set of modules kept for an image that was not written goes, and
# so does the bundle it downloaded when it did not finish (a kernel update that failed for want of room left 200 MB of
# these behind, FINDINGS 177). MU300_KERNEL_BUNDLE, a file of the caller's, is never removed.
boot_update() {  # boot_update TAG   (MU300_KERNEL_BUNDLE=FILE uses a local mu300-kernel.tar.gz instead)
    BOOT_BUNDLE=
    boot_update_run "$@"; _bur=$?
    # (a step that ended with its modules half-way: put right before what it unpacked goes)
    modules_settle || _bur=1
    rm -rf "${STAGE:?}/boot" "${BOOTDIR:?}/prev.modules.new"
    [ "$_bur" = 0 ] || [ -z "$BOOT_BUNDLE" ] || [ -n "${MU300_KERNEL_BUNDLE:-}" ] || rm -f "$BOOT_BUNDLE"
    BOOT_MODS_PENDING=
    return "$_bur"
}
# (from the EXIT trap, unpack_abort: a run stopped between the new modules and the image puts the set in place back)
BOOT_MODS_PENDING=
boot_abort() {
    if [ -f "${BOOTDIR:?}/modules.pending" ]; then
        modules_settle >/dev/null 2>&1
    elif [ -n "${BOOT_MODS_PENDING:-}" ] && [ -d "$BOOTDIR/prev.modules.new" ]; then
        prev_modules_restore "$BOOTDIR/prev.modules.new" >/dev/null 2>&1
    fi
    BOOT_MODS_PENDING=
    rm -rf "${STAGE:?}/boot" "${BOOTDIR:?}/prev.modules.new" 2>/dev/null
    return 0
}

boot_update_run() {
    tag=$1 bp=boot_$(linux_slot)
    dev=$(boot_dev "$bp") || { echo "boot: the boot image was not updated" >&2; return 1; }
    psize=$(part_bytes "$dev")
    tmp=${STAGE:?}/boot
    modules_settle || return 1
    rm -rf "$tmp" "${BOOTDIR:?}/prev.modules.new"; mkdir -p "$tmp" "$BOOTDIR"
    kernel_retired_note

    say "boot: kernel and boot image"
    # the image in the Linux slot now: stock header page, kernel, ramdisk; AVB footer in the last 64 bytes (read
    # first: its size is part of the room the step wants, and its kernel says which module sets are still needed)
    dd if="$dev" of="$tmp/hdr" bs=4096 count=1 2>/dev/null
    dd if="$dev" of="$tmp/footer" bs=64 skip=$((psize / 64 - 1)) count=1 2>/dev/null
    [ "$(head -c 8 "$tmp/hdr")" = ANDROID! ] && [ "$(u32 "$tmp/hdr" 40)" = 4 ] ||
        { echo "boot: $bp does not hold a boot image header v4, not touching it" >&2; return 1; }
    [ "$(head -c 4 "$tmp/footer")" = AVBf ] || { echo "boot: $bp has no AVB footer, not touching it" >&2; return 1; }
    ksz=$(u32 "$tmp/hdr" 8); rsz=$(u32 "$tmp/hdr" 12)
    osize=$(be64 "$tmp/footer" 12); vbs=$(be64 "$tmp/footer" 28)
    BOOT_SLOT_KREL=$(image_krel "$dev") BOOT_KEPT_KREL=
    [ ! -s "$BOOTDIR/prev.body" ] || BOOT_KEPT_KREL=$(image_krel "$BOOTDIR/prev.body")
    kernel_set_from_old "$BOOT_SLOT_KREL"
    kernel_sets_remove $(boot_sets_stale)

    bundle=${MU300_KERNEL_BUNDLE:-}
    if [ -z "$bundle" ]; then
        # apply() has fetched it already; for "boot" and "kernel" this is the download, after a look at the room
        asset=$(kernel_asset)
        bundle=$STAGE/$asset
        if [ ! -s "$bundle" ]; then
            _bn=$(kernel_need_kb "$tag"); _bf=$(df -Pk "$DISK" | awk 'NR == 2 { print $4 }'); _bk=$(boot_kept_kb)
            [ $(( ${_bf:-0} + _bk )) -ge "$_bn" ] || { echo "boot: not enough free space on the Linux partition for the kernel: about $((_bn / 1024)) MB needed (its download, the unpacked bundle with its modules, and the boot images), $((${_bf:-0} / 1024)) MB free and $((_bk / 1024)) MB in the boot image kept for rollback-boot. Nothing was changed. mu300-update clean deletes the kept previous versions of the systems" >&2; return 1; }
        fi
        BOOT_BUNDLE=$bundle
        fetch_verified "$tag" "$asset" || { echo "boot: no verified $asset of $tag (kernel $(kernel_choice)), nothing was changed" >&2; return 1; }
    fi
    [ -s "$bundle" ] || { echo "boot: $bundle not found" >&2; return 1; }
    tar -tzf "$bundle" > "$tmp/list" 2>/dev/null || { echo "boot: $bundle is not a readable tar.gz" >&2; return 1; }
    if ! grep -qx './ramdisk-generic.lz4' "$tmp/list"; then
        printf 'boot: release %s predates on-device boot updates; the boot image is unchanged\n' "$tag"
        return 0
    fi
    # A bundle names the devices it runs on (./devices). One without that file is from before the U30 Air: its 5.4
    # ramdisk does not load the U30 Air's modules and its mainline kernel does not bring up its USB (FINDINGS 33,
    # 33c) - on a U30 Air either one boots to a device with no USB at all.
    if ! bundle_runs_here "$bundle" "$tmp/list" "$tmp"; then
        printf 'boot: the kernel of %s does not support the %s; the boot image is unchanged\n' "$tag" "$(this_device)" >&2
        return 1
    fi
    if root_on_sd && ! bundle_has_sd "$bundle" "$tmp/list"; then
        echo "boot: this kernel bundle cannot read the SD card, and this system runs from it; nothing was changed" >&2
        return 1
    fi
    if ! bundle_fits_slot "$bundle" "$tmp/list"; then
        echo "boot: this kernel bundle's init runs only from slot b, and Linux is on $bp; nothing was changed" >&2
        return 1
    fi
    if ! bundle_finds_root "$bundle" "$tmp/list"; then
        echo "boot: $(root_not_found_msg); nothing was changed" >&2
        return 1
    fi

    boot_room "$bundle" "$tmp/list" $(( 2 * (osize / 1024 + 4) )) || return 1

    # one pass over the bundle for what the step uses: kernel, generic ramdisk and - a kernel the systems were not
    # built with (mainline) - its release and modules, which go in below, before the boot image changes, and also when
    # the image is up to date (a system the update just replaced has none yet)
    mods= _bx="./Image ./ramdisk-generic.lz4"
    if grep -qx './kernel.release' "$tmp/list"; then
        mods=1 _bx="$_bx ./kernel.release ./modules"
        for f in modules.builtin modules.builtin.modinfo; do ! grep -qx "./$f" "$tmp/list" || _bx="$_bx ./$f"; done
    fi
    untar -xzf "$bundle" -C "$tmp" $_bx || { echo "boot: unpacking $bundle failed; nothing was changed" >&2; return 1; }
    [ -s "$tmp/Image" ] && [ -s "$tmp/ramdisk-generic.lz4" ] || { echo "boot: no kernel in the bundle" >&2; return 1; }
    { [ -z "$mods" ] || { [ -s "$tmp/kernel.release" ] && modules_complete "$tmp" "$tmp/list"; }; } ||
        { echo "boot: unpacking the modules failed; nothing was changed" >&2; return 1; }
    # what was unpacked is on the disk before a system gets it as second names (#422: empty files after a restart)
    kbanner=
    if [ -n "$mods" ]; then sync; kbanner=$(kernel_banner < "$tmp/Image"); fi
    # unpacked and checked: the download has done its part (a bundle of the caller's stays)
    [ -n "${MU300_KERNEL_BUNDLE:-}" ] || rm -f "$bundle"
    id=$(cat "$tmp/Image" "$tmp/ramdisk-generic.lz4" | sha256sum | cut -d' ' -f1)

    dd if="$dev" of="$tmp/body" bs=4096 count=$((osize / 4096)) 2>/dev/null
    dd if="$dev" bs=4096 skip=$((osize / 4096)) count=$(( (vbs + 4095) / 4096 )) 2>/dev/null | head -c "$vbs" > "$tmp/vbmeta"
    cur=$(sha256sum < "$tmp/body" | cut -d' ' -f1)
    if [ "$cur" = "$(cat "$BOOTDIR/written.sha256" 2>/dev/null)" ] && [ "$id" = "$(cat "$BOOTDIR/installed.id" 2>/dev/null)" ]; then
        if [ -n "$mods" ]; then
            [ -z "$kbanner" ] || modules_pending "$(cat "$tmp/kernel.release")" "$kbanner"
            kernel_modules_into_systems "$tmp" || return 1
            modules_done
        fi
        # the image in place is this release's as well (the same kernel and ramdisk): written down, or check and the
        # Update page offer this release again after every update that did not change the kernel (seen on the U30
        # Air: v2026.10.30 installed, its boot image still called v2026.10.27)
        echo "$tag" > "$BOOTDIR/installed.tag"
        printf 'boot: already up to date (%s)\n' "$tag"
        # (a retired choice whose successor is in place already, as after mu300-update kernel 7.3 by hand: written down)
        kernel_choice_settle "$tmp/kernel.release"
        return 0
    fi
    if [ "$cur" != "$(cat "$BOOTDIR/written.sha256" 2>/dev/null)" ] || [ ! -s "$BOOTDIR/device-ramdisk.lz4" ]; then
        # the image comes from an installer: its whole ramdisk becomes the device segment (its generic files are
        # replaced by the ones appended below)
        roff=$((4096 + (ksz + 4095) / 4096 * 4096))
        head -c "$((roff + rsz))" "$tmp/body" | tail -c "$rsz" > "$BOOTDIR/device-ramdisk.lz4.new"
        [ "$(od -An -tx1 -N4 "$BOOTDIR/device-ramdisk.lz4.new" | tr -d ' \n')" = 02214c18 ] ||
            { rm -f "$BOOTDIR/device-ramdisk.lz4.new"; echo "boot: the ramdisk in $bp is not LZ4 legacy, not touching it" >&2; return 1; }
        mv "$BOOTDIR/device-ramdisk.lz4.new" "$BOOTDIR/device-ramdisk.lz4"
    fi

    # new image: same header with the new sizes, kernel, device segment + generic segment, AVB tail
    nksz=$(fsize "$tmp/Image")
    nrsz=$(( $(fsize "$BOOTDIR/device-ramdisk.lz4") + $(fsize "$tmp/ramdisk-generic.lz4") ))
    cp "$tmp/hdr" "$tmp/new"
    bootimg_assemble "$tmp" "$vbs" "$tmp/Image" "$BOOTDIR/device-ramdisk.lz4" "$tmp/ramdisk-generic.lz4" ||
        { echo "boot: not touching $bp" >&2; return 1; }
    rm -f "$tmp/Image"      # in the new image now

    # keep the current image and the module set it runs with for rollback-boot, then the new modules, then write.
    # Until the image is kept (prev_modules_commit with prev.body) a failure puts the set in place back and leaves
    # the kept image and its set as they were.
    retire_call_audio || { echo "boot: legacy call audio could not be removed" >&2; return 1; }
    prev_modules_save "$tmp" || { echo "boot: keeping the modules in place failed; nothing was changed" >&2; return 1; }
    BOOT_MODS_PENDING=1
    # (the kept set on the disk first: it is what a restart before the image is written puts back)
    [ -z "$mods" ] || [ -z "$kbanner" ] || { sync; modules_pending "$(cat "$tmp/kernel.release")" "$kbanner"; }
    if [ -n "$mods" ] && ! kernel_modules_into_systems "$tmp"; then
        prev_modules_restore "$BOOTDIR/prev.modules.new" >/dev/null; BOOT_MODS_PENDING=; modules_done
        echo "boot: the boot image is unchanged" >&2; return 1
    fi
    # the image read from the slot is the one kept: moved, not copied
    prev_modules_commit
    mv -f "$tmp/body" "$BOOTDIR/prev.body"; cp "$tmp/vbmeta" "$BOOTDIR/prev.vbmeta"; cp "$tmp/footer" "$BOOTDIR/prev.footer"
    BOOT_MODS_PENDING=
    linux_slot > "$BOOTDIR/prev.slot"     # rollback-boot puts it back only on the slot it came from
    unlock_for_trial
    cat "$BOOTDIR/installed.tag" > "$BOOTDIR/prev.tag" 2>/dev/null || echo installer > "$BOOTDIR/prev.tag"
    cat "$BOOTDIR/installed.kernel" > "$BOOTDIR/prev.kernel" 2>/dev/null || echo 5.4 > "$BOOTDIR/prev.kernel"
    sync
    if ! write_boot "$dev" "$psize" "$tmp/new" "$tmp/vbmeta" "$tmp/newfooter"; then
        echo "boot: writing $bp failed verification; restoring the previous image" >&2
        write_boot "$dev" "$psize" "$BOOTDIR/prev.body" "$BOOTDIR/prev.vbmeta" "$BOOTDIR/prev.footer" ||
            echo "boot: RESTORE FAILED - do not reboot into Linux; reinstall with ./install.sh from a computer" >&2
        prev_modules_restore >&2 && modules_done
        return 1
    fi
    sha256sum < "$tmp/new" | cut -d' ' -f1 > "$BOOTDIR/written.sha256"
    echo "$id" > "$BOOTDIR/installed.id"
    echo "$tag" > "$BOOTDIR/installed.tag"
    kernel_choice > "$BOOTDIR/installed.kernel"
    kernel_choice_settle "$tmp/kernel.release"
    modules_done
    # the image that was in the slot is the kept one now: the sets neither image needs go (the one the image kept
    # until now ran with, unless it is still needed)
    BOOT_KEPT_KREL=$BOOT_SLOT_KREL BOOT_SLOT_KREL=$(cat "$tmp/kernel.release" 2>/dev/null || image_krel "$dev")
    kernel_sets_remove $(boot_sets_stale)
    sync
    printf 'boot: updated to %s (kernel %s bytes, ramdisk %s bytes). If it does not start, the device falls back\n' "$tag" "$nksz" "$nrsz"
    printf '      to Android by itself; mu300-update rollback-boot restores the previous image.\n'
    BOOT_CHANGED=1
}

# Ubuntu 26.04 needs a mainline kernel: its GNU tar opens every file below the top with openat2(RESOLVE_BENEATH),
# which 5.4 does not have (5.6 brought it), and fails with ENOSYS instead of falling back - no update or archive
# with folders unpacks there. Other programs of that release can expect more of the kernel still.
ubuntu_release() { sed -n 's/^VERSION_ID="\(.*\)"/\1/p' "$DISK/ubuntu/usr/lib/os-release" 2>/dev/null; }
UBUNTU_2604_KERNEL="Ubuntu 26.04 needs a mainline kernel (6.18 or 7.3): its programs use system calls that 5.4 does not have"

kernel_cmd() {  # kernel [5.4|6.18|7.3]: show or change the kernel, and install it
    mounted_disk
    case ${1:-} in
        '') printf 'kernel: %s (running %s)\n' "$(kernel_choice)" "$(uname -r)"
            ! _kn=$(kernel_retired "$(kernel_chosen)") ||
                printf 'kernel %s was chosen, and it is retired: the next update (mu300-update apply) installs %s\n' "$(kernel_chosen)" "$_kn"
            return 0 ;;
        5.4|6.18|7.3) ;;
        *) # (a retired one is refused with the one that takes its place, rather than taken for it without a word)
           _kn=$(kernel_retired "$1") &&
               die "kernel $1 is retired (kernel.org ended that series) and releases no longer carry it: sudo mu300-update kernel $_kn installs $_kn, the kernel that takes its place (or 6.18, the long-term one)"
           die "usage: mu300-update kernel [5.4|6.18|7.3]" ;;
    esac
    [ "$1" = 5.4 ] && [ "$(ubuntu_release)" = 26.04 ] &&
        die "$UBUNTU_2604_KERNEL (tar cannot unpack folders there). Stay on a mainline kernel, or move Ubuntu back first: sudo MU300_UBUNTU=24.04 mu300-update apply"
    mkdir -p "$BOOTDIR"
    old=$(kernel_choice)
    echo "$1" > "$KERNEL_CHOICE"
    t=${MU300_RELEASE:-$(latest_release)}
    [ -n "$t" ] || { echo "$old" > "$KERNEL_CHOICE"; die "could not reach GitHub ($(offline_why))"; }
    boot_downgrade_ok "$t" || { echo "$old" > "$KERNEL_CHOICE"; die "the $1 kernel was not installed; staying on $old"; }
    if ! boot_update "$t"; then
        echo "$old" > "$KERNEL_CHOICE"
        die "the $1 kernel was not installed; staying on $old"
    fi
    rm -rf "$STAGE"
    sync
    printf '\nkernel %s selected. ' "$1"
    reboot_goes_to_android || printf 'Reboot to start it (mu300-update rollback-boot goes back).\n'
}

rollback_boot() {
    mounted_disk
    [ -s "$BOOTDIR/prev.body" ] || die "no previous boot image kept"
    # The kept image was taken from the slot Linux ran from then (kept before prev.slot existed: b). On the other
    # slot its init may know only b: it would restore the block that boots Linux again and log into Android's boot.
    ps=$(cat "$BOOTDIR/prev.slot" 2>/dev/null || echo b)
    [ "$ps" = "$(linux_slot)" ] ||
        die "the previous boot image was taken from slot $ps, Linux now runs from $(linux_slot); nothing was written"
    dev=$(boot_dev "boot_$(linux_slot)") || die "nothing was written"
    psize=$(part_bytes "$dev")
    retire_call_audio || die "legacy call audio could not be removed; boot was not changed"
    unlock_for_trial
    write_boot "$dev" "$psize" "$BOOTDIR/prev.body" "$BOOTDIR/prev.vbmeta" "$BOOTDIR/prev.footer" ||
        die "writing the previous boot image failed verification"
    prev_modules_restore || die "the previous boot image is back but its modules are not: run mu300-update kernel \"$(cat "$BOOTDIR/prev.kernel" 2>/dev/null)\" before rebooting"
    sha256sum < "$BOOTDIR/prev.body" | cut -d' ' -f1 > "$BOOTDIR/written.sha256"
    rm -f "$BOOTDIR/installed.id"
    cat "$BOOTDIR/prev.tag" > "$BOOTDIR/installed.tag" 2>/dev/null
    # the image that is back belongs to a kernel choice too: without this the next update would reinstall the
    # kernel just rolled back from
    if [ -s "$BOOTDIR/prev.kernel" ]; then
        cat "$BOOTDIR/prev.kernel" > "$KERNEL_CHOICE"
        cat "$BOOTDIR/prev.kernel" > "$BOOTDIR/installed.kernel"
    fi
    sync
    printf 'boot: previous boot image (%s) restored. ' "$(cat "$BOOTDIR/prev.tag" 2>/dev/null || echo unknown)"
    reboot_goes_to_android || printf 'Reboot to start it.\n'
    # (an image of a retired kernel runs as it did, but no release has that kernel: the next update brings its successor)
    ! _kn=$(kernel_retired "$(kernel_chosen)") ||
        printf 'Kernel %s is retired: the next update (mu300-update apply) installs %s again; sudo mu300-update kernel 6.18 moves to the long-term one.\n' "$(kernel_chosen)" "$_kn"
}

# One mu300-update at a time. apply, boot, kernel, rollback, rollback-boot and clean all work in $STAGE: two runs
# started together once both appended their kernel to the same $STAGE/boot/new, and both stopped at the size check
# (a 56 MB "image" that "would reach the persistent log area" - harmless, but puzzling). The second run now says who
# holds the lock and exits 1 before it touches anything. Nothing runs unlocked: when the lock cannot be had, the
# run stops (fails closed).
#   The lock lives in a directory of root's own under /run (root's, so no one else can put anything at that path):
# made here with mode 700, and refused when what is there is a link, not a directory of exactly that mode, or
# someone else's - never in $STAGE (clean deletes it) nor under /tmp or /var/lock, where any login user could plant
# a link or a lock of their own. Inside it, flock(1) on a regular file through fd 9 where flock exists (busybox's
# applet on OpenWrt, util-linux on Ubuntu; the kernel releases it however the run ends), else a directory "held"
# made atomically with the holder's pid in it. A pid read from the lock is digits only and bounded, and the holder
# counts as running only when that pid is alive and is a mu300-update (/proc/PID/cmdline where there is one):
# a lock left by a run that is gone is taken over, with a line saying so, never a denial for good. A run that
# continues with the release's own updater (exec in apply) keeps its pid and fd 9, so it simply locks again.
# check, version and notice (at boot and every 6 hours) only read and do not lock.
LOCK=${MU300_LOCK:-/run/mu300-update}
lock_refuse() { echo "cannot lock: $*; not running" >&2; exit 1; }
lock_pid() {  # lock_pid FILE: the pid in it, when it is one (digits only, at most 8 of them); else nothing
    _lp=$(head -c 16 "$1" 2>/dev/null | tr -d '\n')
    case $_lp in ''|*[!0-9]*) return 0 ;; esac
    [ ${#_lp} -le 8 ] && echo "$_lp"
}
update_alive() {  # update_alive PID: that process runs, and is a mu300-update where /proc can tell
    kill -0 "$1" 2>/dev/null || return 1
    [ -r "/proc/$1/cmdline" ] || return 0
    { tr '\0' ' ' < "/proc/$1/cmdline"; } 2>/dev/null | grep -q mu300-update
}
lock_dir_ok() {  # the lock directory as this run needs it, or a refusal
    [ ! -L "$LOCK" ] || lock_refuse "$LOCK is a symbolic link"
    [ -e "$LOCK" ] || ( umask 077; mkdir "$LOCK" ) 2>/dev/null || [ -d "$LOCK" ] || lock_refuse "cannot make $LOCK"
    [ ! -L "$LOCK" ] || lock_refuse "$LOCK is a symbolic link"
    _ls=$(ls -ldn "$LOCK" 2>/dev/null)
    case $_ls in drwx------*) ;; *) lock_refuse "$LOCK is not a directory of mode 700" ;; esac
    [ "$(printf '%s\n' "$_ls" | awk '{print $3}')" = "$(id -u)" ] || lock_refuse "$LOCK is not ours"
}
lock_take() {
    lock_dir_ok
    if have flock; then
        # never a link, not even a dangling one (>> would make its target), and nothing but a regular file
        [ ! -L "$LOCK/lock" ] && { [ ! -e "$LOCK/lock" ] || [ -f "$LOCK/lock" ]; } || lock_refuse "$LOCK/lock is not a regular file"
        exec 9>>"$LOCK/lock" || lock_refuse "cannot open $LOCK/lock"
        if ! flock -n 9; then
            # This run, continued with the release's updater (apply execs it: the same process id, and the lock file
            # says so): the lock is held by what the updater before it left behind - its keep-alive's ping or sleep,
            # which had the lock's descriptor and outlive it by a few seconds. Up to v2026.10.24 that ended every
            # update whose release brought another mu300-update with "another mu300-update is running" (FINDINGS 81).
            # They are gone within seconds; and should one stay, the lock is still this run's.
            [ -n "${MU300_SELF_UPDATED:-}" ] && [ "$(lock_pid "$LOCK/lock")" = "$$" ] || lock_busy "$(lock_pid "$LOCK/lock")"
            _n=0
            until flock -n 9; do _n=$((_n + 1)); [ "$_n" -lt 10 ] || break; sleep 1; done
        fi
        echo $$ > "$LOCK/lock"
        return 0
    fi
    _try=0
    until ( umask 077; mkdir "$LOCK/held" ) 2>/dev/null; do
        [ -d "$LOCK/held" ] || lock_refuse "cannot make $LOCK/held"
        _pid=$(lock_pid "$LOCK/held/pid")
        [ "$_pid" = "$$" ] && { LOCK_DIR=1; return 0; }     # this run, continued with the release's updater
        # a holder writes its pid right after making the directory: none a second later is a run that is gone
        [ -n "$_pid" ] || { sleep 1; _pid=$(lock_pid "$LOCK/held/pid"); }
        if [ -n "$_pid" ] && update_alive "$_pid"; then lock_busy "$_pid"; fi
        [ "$_try" = 0 ] || lock_busy "$_pid"
        echo "taking over the lock of a mu300-update that is gone${_pid:+ (pid $_pid)}" >&2
        rm -rf "$LOCK/held"; _try=1
    done
    echo $$ > "$LOCK/held/pid"
    LOCK_DIR=1
}
lock_busy() {  # lock_busy [PID]: the refusal, and the end
    _p=$1
    [ -n "$_p" ] && update_alive "$_p" || _p=
    echo "another mu300-update is running${_p:+ (pid $_p)}" >&2
    exit 1
}
lock_drop() {
    [ -n "${LOCK_DIR:-}" ] && [ "$(lock_pid "$LOCK/held/pid")" = "$$" ] && rm -rf "$LOCK/held"
    LOCK_DIR=
}

# Older boot images lose the mobile downlink for good when the IPA goes idle and fails to power off
# (docs/FINDINGS.md 32) - after about two quiet minutes, which the unpacking alone takes. A packet every few seconds
# keeps it from going idle while the update runs (two targets, one of them reachable from mainland China).
keepalive_start() {
    have ping || return 0
    # (9>&-: without the lock's descriptor - a ping or sleep of this that outlives the run would hold the lock)
    ( while :; do ping -c1 -W2 1.1.1.1 >/dev/null 2>&1 & ping -c1 -W2 223.5.5.5 >/dev/null 2>&1; sleep 3; done ) 9>&- &
    KEEPALIVE=$!
}
keepalive_stop() { [ -n "${KEEPALIVE:-}" ] && kill "$KEEPALIVE" 2>/dev/null; KEEPALIVE=; }
offline_hint() {
    # (behind the kill switch the modem is not what is wrong)
    ! vpn_ks_blocks || return 0
    printf 'If this device ran for a while without traffic, older boot images can lose mobile data\n' >&2
    printf 'until the next boot: reboot, then run mu300-update apply right away.\n' >&2
}
# fetch_stop RC: apply ends after fetch_verified failed with RC. A refused release (3) is not a download to continue,
# and its log should not send the owner looking for a network fault (seen on the U30 Air, an unsigned release).
fetch_stop() {
    [ "$1" != 3 ] || die "nothing was changed"
    ! vpn_ks_blocks || die "nothing was changed: the download was $(offline_why)"
    offline_hint; die "nothing was changed; run mu300-update apply again to continue the download"
}

# While the update unpacks and writes the boot image, mobile data is left alone: the watchdog of the connection would
# otherwise redial (AT commands, the IPA brought down and up) in the middle of it. The connection stays as it is.
pause_data() {
    DATA_PAUSED=
    if have systemctl && systemctl -q is-active mu300-mobile-data-watch 2>/dev/null; then
        systemctl stop mu300-mobile-data-watch && DATA_PAUSED=1
    fi
}
resume_data() {
    [ -n "${DATA_PAUSED:-}" ] || return 0
    DATA_PAUSED=
    systemctl start mu300-mobile-data-watch 2>/dev/null || true
}

apply() {
    mounted_disk
    # (apply --from: the source is checked and names the release, see from_begin)
    [ -z "${MU300_FROM:-}" ] || from_begin
    tag=${MU300_RELEASE:-$(latest_release)}
    [ -n "$tag" ] || { offline_hint; die "could not reach GitHub ($(offline_why))"; }
    # (an older release than what is installed only when asked for, whatever the source: see downgrade_ok. Before
    # this run hands over to that release's own updater, which may not carry over everything you added)
    downgrade_ok "$tag" $(apply_targets "$@") || die "nothing was changed"
    # The release's own updater does the update when it differs from this one (releases from v2026.09.28 on
    # carry it): fixes to the update itself then reach a device before the update runs, not one update later.
    # $0 is usually the link in /usr/local/bin: the file it points to is replaced, never the link (a file there
    # would be kept by every later update, with usr/local, and hide the updater of the system)
    self=$(readlink -f "$0" 2>/dev/null || echo "$0")
    if [ -z "${MU300_SELF_UPDATED:-}" ] && fetch_verified "$tag" mu300-update 2>/dev/null &&
        ! cmp -s "$STAGE/mu300-update" "$self" && sh -n "$STAGE/mu300-update" && from_handover "$STAGE/mu300-update"; then
        printf 'continuing with the mu300-update of %s\n' "$tag"
        keepalive_stop
        cp "$STAGE/mu300-update" "$self.new" && chmod 755 "$self.new" && mv -f "$self.new" "$self" 2>/dev/null || true
        MU300_SELF_UPDATED=1 MU300_RELEASE=$tag exec sh "$STAGE/mu300-update" apply "$@"
    fi
    list=
    for a in "$@"; do
        # the packages installed on the device are not installed again (their settings are set aside all the same)
        # --no-rollback: the previous system is not kept as <os>.old, and your files are not copied but become the
        # new system's (the carry block's link mode): for a device without the room for both
        case $a in --no-reinstall) MU300_KEEP_PACKAGES=0 ;; --no-rollback) CARRY_MODE=link ;; *) list="$list $a" ;; esac
    done
    [ -n "$list" ] || list=$(installed_systems)
    [ -z "${FROM_ONLY:-}" ] || list=$FROM_ONLY     # (a Magisk zip holds one system)
    BOOT_CHANGED=
    SYSTEM_CHANGED=
    NO_ROLLBACK=
    [ "${MU300_UBUNTU:-}" = 26.04 ] && [ "$(kernel_choice)" = 5.4 ] &&
        die "$UBUNTU_2604_KERNEL. Change the kernel first: sudo mu300-update kernel 6.18 (or 7.3)"
    todo=
    for os in $list; do
        case $os in ubuntu|openwrt|openwrt-luci) ;; *) die "unknown system '$os'" ;; esac
        [ -d "$DISK/$os" ] || die "$os is not installed"
        # already there: an older mu300-update installed this release's system, and this run is for the boot image
        # (moving Ubuntu to the other release with MU300_UBUNTU is an update even at the same tag)
        other=
        [ "$os" = ubuntu ] && [ -n "${MU300_UBUNTU:-}" ] &&
            [ "$MU300_UBUNTU" != "$(sed -n 's/^VERSION_ID="\(.*\)"/\1/p' "$DISK/ubuntu/etc/os-release" 2>/dev/null)" ] && other=1
        if [ "$(cat "$DISK/$os$VERSION_FILE" 2>/dev/null)" = "$tag" ] && [ -z "${MU300_FORCE:-}$other" ]; then
            printf '%s: already %s\n' "$os" "$tag"
            continue
        fi
        is_root "$DISK/$os.old" && die "$os was updated already and is still running the old copy: reboot first"
        todo="$todo $os"
    done

    # Everything is downloaded and checked first, and only then is anything changed. Older boot images can lose
    # the mobile downlink after two quiet minutes (docs/FINDINGS.md 32): a download that followed the minutes of
    # unpacking hung there, and a device that reset in the middle of writing its boot image could only start Android.
    clean_broken
    # (what an update that was cut off left - a half-unpacked <os>.new - would count against the room below)
    delta_clean "$DISK"
    say "downloading $tag"
    # The room: the download, what unpacking the new images writes - only the files that are not in the installed
    # systems as they are (update_need, the delta block) - and a copy of what the user added for the rollback
    # (carry_need). A release without the manifests of its images: space_needed's rule, as before.
    free=$(df -Pk "$DISK" | awk 'NR==2 {print $4}')
    # (the boot image kept for rollback-boot is given up when the kernel step is short of room: boot_kept_kb)
    kfree=$(boot_kept_kb)
    if [ -z "$todo" ]; then
        # only the kernel and the extras: what the kernel step wants (space_needed's 1 GB for a whole system refused
        # it on a device that had the room for it, FINDINGS 177)
        need=$(kernel_need_kb "$tag")
        [ $((free + kfree)) -gt "$need" ] || { rm -rf "${STAGE:?}"; die "not enough free space on the Linux partition for the kernel: about $((need / 1024)) MB needed (its download, the unpacked bundle with its modules, and the boot images), $((free / 1024)) MB free. Nothing was changed. mu300-update clean deletes the kept previous versions of the systems"; }
    elif need=$(update_need "$tag" $todo); then
        [ $((free + kfree)) -gt "$need" ] || { rm -rf "$STAGE"; die "not enough free space on the Linux partition: $((need / 1024)) MB needed, $((free / 1024)) MB free (the download, the new release's files that are not in the installed system as they are, and a copy of what you added to it for the previous version kept for a rollback). Nothing was changed. mu300-update clean deletes the kept previous versions; mu300-update apply --no-rollback keeps none, and needs no room for your files"; }
    else
        need=$(space_needed "$(echo $todo | wc -w)" "$(carry_need $todo)")
        [ "$free" -gt "$need" ] || die "not enough free space on the Linux partition: $((need / 1024)) MB needed, $((free / 1024)) MB free (about 1 GB, plus 1 GB for every system to update, plus a copy of what you added to it for the previous version kept for a rollback). mu300-update clean deletes the kept previous versions; mu300-update apply --no-rollback keeps none, and needs no room for your files"
    fi
    # (where the release has the diff from the installed image, only that: the diff block)
    for os in $todo; do
        diff_fetch "$tag" "$os" || fetch_verified "$tag" "$(rootfs_asset "$os")" || fetch_stop $?
    done
    # (the release that was judged - signature, downgrade - is the one these files are: see payload_is)
    payload_is "$tag" $todo || die "nothing was changed"
    # the extras of the release: an installed one follows it (a release without it: r=2, the installed one stays)
    extras=
    for x in $(extras_to_fetch "$tag"); do
        fetch_verified "$tag" "$(extra_asset "$x")"; r=$?
        [ "$r" = 0 ] && { extras="$extras $x"; continue; }
        [ "$r" = 2 ] || fetch_stop "$r"
    done
    # the VPN module, from its own repository: a device that uses the VPN gets it, or the update stops here
    modules_fetch "$tag" "$todo"
    boot_asset=
    if [ -z "${MU300_KERNEL_BUNDLE:-}" ]; then
        kernel_retired_note
        boot_asset=$(kernel_asset)
        fetch_verified "$tag" "$boot_asset"; r=$?
        # a release without this bundle leaves the boot image alone (boot_update says so); anything else stops here
        [ "$r" = 0 ] || [ "$r" = 2 ] || fetch_stop "$r"
    fi
    # the boot image comes last, after the systems: a bundle whose init cannot find this disk stops the whole update
    # here, before anything is changed (#290), not after the systems were replaced
    _ab=${MU300_KERNEL_BUNDLE:-${boot_asset:+$STAGE/$boot_asset}}
    if [ -n "$_ab" ] && [ -s "$_ab" ] && tar -tzf "$_ab" > "$STAGE/kernel.list" 2>/dev/null &&
        grep -qx './ramdisk-generic.lz4' "$STAGE/kernel.list" && ! bundle_finds_root "$_ab" "$STAGE/kernel.list"; then
        rm -f "$STAGE/kernel.list"
        die "$(root_not_found_msg). Nothing was changed"
    fi
    rm -f "$STAGE/kernel.list"
    # the diffs become the new systems now, while one that does not can still be replaced by the whole image
    diffs_unpack "$tag" $todo
    echo "all files are here and verified; from now on the network is not needed"

    retire_call_audio || die "legacy call audio could not be removed; update stopped before replacing systems"
    pause_data
    EXTRA_CHANGED=
    modules_install "$tag"
    # the verified module copies are gone once installed
    rm -rf "$STAGE/module"
    module_vdir_clean
    for os in $todo; do
        apply_one "$os" "$tag"
        SYSTEM_CHANGED=1
    done
    modules_link "$todo"
    extras_install "$tag" "$extras"
    panel_configure "$todo"
    # the kernel goes with the modules of the systems just installed, so it follows them
    boot_ok=1
    boot_update "$tag" || { boot_ok=; printf '\nThe boot image was not updated (see above)%s.\n' "${SYSTEM_CHANGED:+; the systems were}"; }
    resume_data
    [ -z "$boot_ok" ] || rm -rf "$STAGE"
    if [ -z "$SYSTEM_CHANGED$BOOT_CHANGED" ]; then
        [ -n "$boot_ok" ] || return 1
        if [ -n "$EXTRA_CHANGED" ]; then printf '\nThe extras are up to date now.\n'; else printf '\nNothing to do.\n'; fi
        return 0
    fi
    if [ -z "$SYSTEM_CHANGED" ]; then
        if reboot_goes_to_android; then printf 'The previous boot image is kept: mu300-update rollback-boot\n'
        else printf '\nReboot to start the new kernel. The previous boot image is kept: mu300-update rollback-boot\n'; fi
        return 0
    fi
    kept='The previous version is kept: mu300-update rollback'
    [ -z "$NO_ROLLBACK" ] || kept='The previous version is not kept (--no-rollback): there is no rollback of this update'
    case " $list " in
        *" $(running_os) "*)
            if reboot_goes_to_android; then printf '%s\n' "$kept"
            else printf '\nReboot to start the updated %s. %s\n' "$(running_os)" "$kept"; fi
            # the new system has your files as they were when this ran
            printf 'Reboot soon: what changes in the running system from now on stays in the previous one.\n' ;;
        *) reboot_goes_to_android || printf '\nDone. The updated system is used the next time you switch to it.\n' ;;
    esac
}

# <os>.broken is what a rollback left behind: the system it rolled back from, kept until the reboot because it may
# be the one running. Once it is not running any more nothing needs it (it was the newer version: apply installs it
# again), so apply removes it - before counting free space, as it is a whole system (655 MB on the second F50).
# apply --no-rollback leaves the system it replaced under the same name (apply_one), for the same reason.
clean_broken() {
    for os in $SYSTEMS; do
        [ -d "$DISK/$os.broken" ] || continue
        is_root "$DISK/$os.broken" && continue
        rm -rf "$DISK/$os.broken" && printf '%s: removed the copy left by a rollback (%s.broken)\n' "$os" "$os"
    done
    return 0
}

rollback() {
    mounted_disk
    list=$*
    [ -n "$list" ] || list=$(installed_systems)
    done_any=
    for os in $list; do
        [ -d "$DISK/$os.old" ] || { printf '%s: no previous version kept\n' "$os"; continue; }
        sync
        is_root "$DISK/$os.old" && { printf '%s: the previous version is the one running now: reboot first\n' "$os"; continue; }
        is_root "$DISK/$os.broken" || rm -rf "$DISK/$os.broken"
        mv "$DISK/$os" "$DISK/$os.broken" || die "$os: could not move the current system aside"
        mv "$DISK/$os.old" "$DISK/$os" || { mv "$DISK/$os.broken" "$DISK/$os"; die "$os: rollback failed (current system restored)"; }
        # the running system is still in use until the reboot: its copy stays as <os>.broken for now (the next
        # rollback or "clean" after the reboot removes it)
        is_root "$DISK/$os.broken" || rm -rf "$DISK/$os.broken"
        sync
        printf '%s: rolled back to %s\n' "$os" "$(cat "$DISK/$os$VERSION_FILE" 2>/dev/null || echo unknown)"
        done_any=1
    done
    [ -n "$done_any" ] && { printf '\n'; reboot_goes_to_android || printf 'Reboot to start it.\n'; }
}

clean() {
    mounted_disk
    for os in $SYSTEMS; do
        if is_root "$DISK/$os.old"; then printf '%s: the previous version is still running: reboot first\n' "$os"
        elif [ -d "$DISK/$os.old" ]; then rm -rf "$DISK/$os.old" && printf '%s: previous version deleted\n' "$os"; fi
        is_root "$DISK/$os.broken" || rm -rf "$DISK/$os.broken"
    done
    rm -rf "$STAGE"
    sync
    df -h "$DISK" | tail -1
}

# ---- for a panel: status, the releases, an update from a file, release signatures ---------------------------------
# What a page needs to update the device from a browser (LuCI's System > Update; docs/FINDINGS.md 86), and nothing
# that changes what an update does or keeps. All of it is below this line, except the few lines that call it:
# fetch_verified (the offline source, the signature, the file being fetched), latest_release (the mirror), apply
# (from_begin, the system of an offline source, the updater it continues with) and the commands at the end.
#   status [--sizes]   one JSON object, no network: the systems and their releases, what is kept for a rollback, the
#                      kernel and the boot image, the default boot, free space, who holds the lock, the note
#   releases           one JSON object: the newest release and, when there is one newer than it, the newest
#                      pre-release, each with what this device would download
#   inspect FILE|DIR   one JSON object: what an offline source says it is, its SHA-256, whether its files match,
#                      whether it is for this device, how its signature checks. Changes nothing.
#   apply --from FILE|DIR [--unsigned] [--downgrade]   update from that source instead of GitHub
# Every string in the JSON goes through jv, which lets only harmless characters through: nothing needs escaping.
jv() { printf '%s' "$1" | tr -cd 'A-Za-z0-9._+:,()@ /-' | cut -c1-200; }
jstr() { if [ -n "$1" ]; then printf '"%s"' "$(jv "$1")"; else printf null; fi; }      # a string, or null when empty
jnum() { case $1 in ''|*[!0-9]*) printf null ;; 0) printf 0 ;; 0*) printf null ;; *) printf '%s' "$1" ;; esac; }
mtime() { _mt=$(date -r "$1" +%s 2>/dev/null) || _mt=; jnum "$_mt"; }
# --- release-tag begin
# The release tags (docs/FINDINGS.md 125): vYYYY.MM.DD up to v2026.10.27, where the "day" was a counter, and from then
# on vYYYY.MM.DD.N: the real (UTC) day the release was built, N = 1..99 for the releases of that day. Every four-field
# tag is newer than every three-field one; four-field tags compare by the date, then by N, as numbers. The same block,
# word for word, is in tools/releases.sh (install.sh, make-release.sh), mu300-update and tools/android-install.sh
# (tests/test_releases.py holds the copies to each other and to tests/fixtures/release-tags.tsv).
# tag_ok TAG: TAG is a release tag (in the shell's own patterns: no grep, no locale, no regex engine to differ)
tag_ok() {
    case $1 in
        v[0-9][0-9][0-9][0-9].[0-9][0-9].[0-9][0-9]) return 0 ;;
        v[0-9][0-9][0-9][0-9].[0-9][0-9].[0-9][0-9].[1-9]|v[0-9][0-9][0-9][0-9].[0-9][0-9].[0-9][0-9].[1-9][0-9]) ;;
        *) return 1 ;;
    esac
    case ${1#v?????} in 0[1-9].*|1[0-2].*) ;; *) return 1 ;; esac
    case ${1#v????????} in 0[1-9].*|[12][0-9].*|3[01].*) ;; *) return 1 ;; esac
}
# tag_key TAG: a number in the order of the releases (1YYYYMMDD00 for vYYYY.MM.DD, 2YYYYMMDDNN for vYYYY.MM.DD.N);
# nothing and status 1 for what is no release tag
tag_key() {
    tag_ok "$1" || return 1
    case $1 in
        *.*.*.*) _tn=${1##*.}; [ ${#_tn} = 2 ] || _tn=0$_tn; _tk=${1%.*}; _te=2 ;;
        *) _tn=00; _tk=$1; _te=1 ;;
    esac
    _tk=${_tk#v}; _td=${_tk#*.}
    echo "$_te${_tk%%.*}${_td%.*}${_td#*.}$_tn"
}
# newer A B: release A is newer than release B; false when either is no release tag. The key is compared in two
# parts (the era and the date, nine digits; then N without its leading zero), so that no shell's integers overflow
# and none reads 08 as octal.
newer() {
    _na=$(tag_key "$1") && _nb=$(tag_key "$2") || return 1
    [ "${_na%??}" -gt "${_nb%??}" ] && return 0
    [ "${_na%??}" = "${_nb%??}" ] || return 1
    _na=${_na#?????????}; _nb=${_nb#?????????}
    [ "${_na#0}" -gt "${_nb#0}" ]
}
# --- release-tag end
# space_needed N [CARRY_KB]: the space an update wants free on the Linux partition, in KiB, for N systems - about
# 1 GB, and 1 GB for each system's download and image - and CARRY_KB, what the carry block copies beside the previous
# versions (carry_need). The one rule: apply refuses with it, and the panel shows it.
space_needed() { echo $((1000000 + 1000000 * $1 + ${2:-0})); }

# /etc/mu300/update-source: another place to take the releases from (a mirror on the LAN, a copy where GitHub cannot
# be reached), for the command and the panel alike. Root's own regular file, lines NAME=URL with these names only;
# the environment wins. MU300_API_URL stands for https://api.github.com/repos/REPO (releases/latest and releases
# below it), MU300_DOWNLOAD_URL for https://github.com/REPO/releases/download (TAG/FILE below it).
SOURCE_CONF=${MU300_SOURCE_CONF:-$CONF/update-source}
# The fallback state of the run a self-update handed over from (mirror_fell_back exports MU300_MIRROR_FELL_BACK):
# apply does not start a new process for the updater of the release it carries, it execs it, so this environment is
# the one the handover left. That run took the rest of its files from github.com, and this one does the same -
# rather than reading the source file again, waiting for the same mirror and saying the line a second time.
mirror_fell_back_inherited() {
    [ -n "${MU300_MIRROR_FELL_BACK:-}" ] || return 0
    SOURCE_FELL_BACK=1
    # the file is left out of it for this run: what it names is a mirror that was just found unreachable
    MIRROR_IGNORED=1
}
source_conf() {
    mirror_fell_back_inherited
    [ -z "${MIRROR_IGNORED:-}" ] || return 0
    [ -f "$SOURCE_CONF" ] && [ ! -L "$SOURCE_CONF" ] || return 0
    _sc=$(ls -ln "$SOURCE_CONF" 2>/dev/null)
    case $_sc in -????-??-?*) ;; *) echo "$SOURCE_CONF is writable by others: ignored" >&2; return 0 ;; esac
    [ -O "$SOURCE_CONF" ] || { echo "$SOURCE_CONF is not ours: ignored" >&2; return 0; }
    while IFS='=' read -r _sk _sv; do
        case $_sk in
            MU300_API_URL|MU300_DOWNLOAD_URL)
                printf '%s\n' "$_sv" | grep -Eqx 'https?://[A-Za-z0-9._:/-]{1,200}' || continue
                case $_sk in
                    MU300_API_URL) [ -n "${MU300_API_URL:-}" ] || MU300_API_URL=$_sv ;;
                    MU300_DOWNLOAD_URL) [ -n "${MU300_DOWNLOAD_URL:-}" ] || MU300_DOWNLOAD_URL=$_sv ;;
                esac ;;
            # the one line of this file that is not an address: it decides whether a run whose mirror cannot be
            # reached takes the release from github.com (the default) or fails as it did before there was a mirror
            MU300_MIRROR_FALLBACK) case $_sv in 0|1) MIRROR_FALLBACK=$_sv ;; esac ;;
        esac
    done < "$SOURCE_CONF"
}

# -- release signatures. A release is trusted today because it comes from GitHub over TLS and matches its
# SHA256SUMS. A signature of SHA256SUMS (SHA256SUMS.sig: Ed25519, in the format of OpenWrt's usign and OpenBSD's
# signify, made by the release workflow from a key that is a repository secret) ties the files to the project
# whatever brought them: a mirror, a memory stick, an upload. The public key is part of the system, RELEASE_PUB -
# beside the programs, not in /etc/mu300, which an update carries over from the old system as a whole (a device
# would never get the key, nor a new one). Without that file nothing is checked and everything is as it was.
# The key is only ever this file of the installed system: never one a release, a zip or a directory brings, and
# only as root's own regular file that nobody else can write (key_state) - anything else there is not "no key",
# which would let a release through as before signing, but a key that cannot be trusted, and stops every update.
RELEASE_PUB=${MU300_RELEASE_PUB:-/opt/mu300/lib/release.pub}
# key_state: none (this system has no release key), ok, or unsafe (a link, not a regular file, not ours, or
# writable by group or others)
key_state() {
    [ -e "$RELEASE_PUB" ] || [ -L "$RELEASE_PUB" ] || { echo none; return 0; }
    [ -f "$RELEASE_PUB" ] && [ ! -L "$RELEASE_PUB" ] && [ -s "$RELEASE_PUB" ] || { echo unsafe; return 0; }
    _ks=$(ls -ln "$RELEASE_PUB" 2>/dev/null)
    case $_ks in -????-??-?*) ;; *) echo unsafe; return 0 ;; esac
    [ -O "$RELEASE_PUB" ] || { echo unsafe; return 0; }
    echo ok
}
# sig_raw FILE: a key or a signature without its comment line, as bytes
sig_raw() { sed -n 2p "$1" | openssl base64 -d -A 2>/dev/null; }
# sig_state SUMS SIG: valid, bad, unsigned (there is no SIG), nokey (this system has no release key), badkey (what
# is at the key's place is not a key of root's own) or notool (nothing here can check a signature). usign where
# there is one (OpenWrt), else openssl (Ubuntu; 3.0 or newer). Only "valid" ever says the files are the project's.
sig_state() {
    case $(key_state) in none) echo nokey; return 0 ;; unsafe) echo badkey; return 0 ;; esac
    [ -s "$2" ] || { echo unsigned; return 0; }
    if have usign; then
        if usign -V -q -m "$1" -p "$RELEASE_PUB" -x "$2" >/dev/null 2>&1; then echo valid; else echo bad; fi
        return 0
    fi
    have openssl && have od || { echo notool; return 0; }
    _sd=$(mktemp -d 2>/dev/null) || { echo notool; return 0; }
    # the key is "Ed", its 8-byte number and 32 bytes; the signature "Ed", the number and 64 bytes. openssl wants
    # the key as DER (the 12 bytes every Ed25519 public key starts with, then the 32).
    sig_raw "$RELEASE_PUB" > "$_sd/pub"; sig_raw "$2" > "$_sd/sig"
    _st=bad
    if [ "$(fsize "$_sd/pub")" = 42 ] && [ "$(fsize "$_sd/sig")" = 74 ] &&
        [ "$(head -c 10 "$_sd/pub" | od -An -tx1)" = "$(head -c 10 "$_sd/sig" | od -An -tx1)" ]; then
        { printf '\060\052\060\005\006\003\053\145\160\003\041\000'; tail -c 32 "$_sd/pub"; } > "$_sd/der"
        tail -c 64 "$_sd/sig" > "$_sd/raw"
        if openssl pkeyutl -verify -pubin -inkey "$_sd/der" -keyform DER -rawin -in "$1" -sigfile "$_sd/raw" >/dev/null 2>&1; then
            _st=valid
        elif ! openssl pkeyutl -help 2>&1 | grep -q -- -rawin; then _st=notool
        fi
    fi
    rm -rf "${_sd:?}"
    echo "$_st"
}
# stage_private: the staging directory, root's own and closed to everyone else before anything is put into it or
# checked in it: what is verified there is what is unpacked minutes later
stage_private() {
    [ ! -L "$STAGE" ] || { echo "$STAGE is a symbolic link: not used" >&2; return 1; }
    # one that others could write into (made by an older updater with another umask, or by hand) may hold what
    # they put there - a link under a name this writes to: it is emptied, not trusted
    if [ -d "$STAGE" ] && [ -O "$STAGE" ]; then
        case $(ls -ldn "$STAGE" 2>/dev/null) in d????-??-?*) ;; *) rm -rf "${STAGE:?}" ;; esac
    fi
    ( umask 077; mkdir -p "$STAGE" ) 2>/dev/null
    [ -d "$STAGE" ] && [ ! -L "$STAGE" ] && [ -O "$STAGE" ] ||
        { echo "$STAGE is not a directory of our own: not used" >&2; return 1; }
    chmod 700 "$STAGE"
}
# tag_sha TAG: the checksum of the file mu300-release of that release (its tag and a newline). SHA256SUMS lists it,
# so the signature of SHA256SUMS covers which release the checksums are of: a signed SHA256SUMS of one release
# cannot be handed out under the name of another.
tag_sha() { printf '%s\n' "$1" | sha256sum | cut -d' ' -f1; }
# sums_trusted TAG BASE: is $STAGE/SHA256SUMS of TAG what the project signed? Decided once per run (SUMS_OK), and
# the file that was judged is pinned by its hash (SUMS_PIN): every later look at it is at those very bytes, or the
# run stops. The rules are sums_verdict's.
SUMS_OK= SUMS_PIN=
sums_trusted() {
    if [ "$SUMS_OK" = "$1" ]; then
        [ -n "$SUMS_PIN" ] && [ "$(sha_of "$STAGE/SHA256SUMS")" = "$SUMS_PIN" ] && return 0
        echo "SHA256SUMS of $1 changed after it was checked: nothing more is taken from it" >&2
        return 1
    fi
    # the signature belongs to the SHA256SUMS just fetched; a kept SHA256SUMS keeps the one fetched with it
    if [ "$(key_state)" != none ] && [ "${SUMS_FETCHED:-}" = "$1" ]; then
        rm -f "${STAGE:?}/SHA256SUMS.sig"
        _sg=$(fetch_stdout "$2/SHA256SUMS.sig" 2>/dev/null) && [ -n "$_sg" ] && ( umask 077; printf '%s\n' "$_sg" > "$STAGE/SHA256SUMS.sig" )
    fi
    # one copy is judged and pinned: its hash is taken first, so nothing can be put in its place in between
    SUMS_PIN=$(sha_of "$STAGE/SHA256SUMS") || return 1
    sums_verdict "$1" "$(sig_state "$STAGE/SHA256SUMS" "$STAGE/SHA256SUMS.sig")" "release $1" "$STAGE/SHA256SUMS" || { SUMS_PIN=; return 1; }
    [ "$(sha_of "$STAGE/SHA256SUMS")" = "$SUMS_PIN" ] || { SUMS_PIN=; echo "SHA256SUMS of $1 changed while it was checked" >&2; return 1; }
    SUMS_OK=$1
}
# sums_verdict TAG STATE WHAT SUMS: may the checksums SUMS, whose signature is in STATE, be used as release TAG's?
#   - a signature that does not match, or a key file that is not root's own: never, whatever is said;
#   - checksums that name another release than TAG (their mu300-release line, tag_sha): never; and signed checksums
#     that name none are not taken as signed, since nothing in them says which release they are;
#   - valid: yes;
#   - this system has no release key, and the release comes from GitHub or a mirror: yes, as before signing (there
#     is nothing to check with; such a system trusts the connection, as it always did);
#   - everything else - no signature, no tool to check one, and any file or directory brought to the device, which
#     has no origin at all: only with the owner's word, MU300_ALLOW_UNSIGNED=1 (apply --unsigned). A system with a
#     key takes no unsigned release silently, older or newer: taking the signature away is not a way in.
sums_verdict() {
    case $2 in
        bad) echo "the signature of $3 does not match the project's release key: not used" >&2; return 1 ;;
        badkey) echo "the release key of this system ($RELEASE_PUB) is not a file of root's own: nothing is trusted with it, and nothing is updated" >&2; return 1 ;;
    esac
    _sv=$(sums_want "$4" mu300-release)
    if [ -n "$_sv" ] && [ "$_sv" != "$(tag_sha "$1")" ]; then
        echo "$3: these are the checksums of another release than $1: not used" >&2; return 1
    fi
    case $2 in
        valid)
            [ -n "$_sv" ] || { echo "$3 is signed, but its checksums do not say which release they are: not used" >&2; return 1; }
            echo "$3: signed with the project's release key"; return 0 ;;
        nokey) [ -n "${MU300_FROM:-}" ] || return 0 ;;
    esac
    if [ -n "${MU300_ALLOW_UNSIGNED:-}" ]; then
        echo "$3 is not signed, or cannot be checked here ($2): used because you said so" >&2
        return 0
    fi
    echo "$3 is not signed with the project's release key ($2): not used (MU300_ALLOW_UNSIGNED=1, or apply --unsigned, takes it anyway)" >&2
    return 1
}
# apply_targets ARG...: the systems an apply with these arguments is about (the named ones, else all installed; a
# zip's one), for downgrade_ok
apply_targets() {
    [ -z "${FROM_ONLY:-}" ] || { echo "$FROM_ONLY"; return 0; }
    _at=
    for _aa in "$@"; do case $_aa in -*) ;; *) _at="$_at $_aa" ;; esac; done
    [ -n "$_at" ] || _at=$(installed_systems)
    echo $_at
}
# downgrade_ok TAG OS...: none of these systems is newer than TAG - or going back was asked for in words
# (MU300_ALLOW_DOWNGRADE=1, apply --downgrade; the one way to say it: the installers' MU300_DOWNGRADE=yes is a
# setting of the zip, never read here). An old release is a correctly made, correctly signed release with the faults
# that were fixed since: whoever can hand the device one (a mirror, a file) must not be able to put it back by that
# alone. And the update is done by that release's own updater and image: one from before the carry block keeps only
# a list of places (keep_list), and what else the user added would be gone from the system. For every source, and
# before the release's own updater is given the run.
downgrade_ok() {
    _dt=$1; shift
    [ -z "${MU300_ALLOW_DOWNGRADE:-}" ] || return 0
    for _do in "$@"; do
        _di=$(cat "$DISK/$_do$VERSION_FILE" 2>/dev/null)
        newer "$_di" "$_dt" || continue
        echo "$_do is $_di and $_dt is older: going back to an older release needs --downgrade, as the older release's updater may not carry over everything you added to the system (mu300-update rollback goes back to the kept version without one, with your files as they were then)" >&2
        return 1
    done
    # (an update also writes the release's kernel and boot image: the same rule for what is there now)
    _di=$(cat "$BOOTDIR/installed.tag" 2>/dev/null)
    if newer "$_di" "$_dt"; then
        echo "the boot image is $_di and $_dt is older: going back to an older release needs --downgrade (mu300-update rollback-boot goes back to the kept one without)" >&2
        return 1
    fi
    return 0
}
# payload_is TAG OS...: the root filesystem staged for each of these systems is release TAG's - its own
# etc/mu300/image-version says so. Every gate before this (the signature, the downgrade rule, what the page showed)
# judged the name TAG; what is installed is the files. Where the checksums are signed the two are bound already
# (tag_sha); where they are not - an unsigned file taken on the owner's word, a mirror on a system without a key -
# nothing else stops an old system handed out under a new name, which the downgrade rule would then never see.
payload_is() {
    _pt=$1; shift
    for _po in "$@"; do
        # (or the diff that stands in for it: its etc/mu300/image-version, which a diff always carries)
        _pf=$STAGE/$(rootfs_asset "$_po")
        [ -s "$_pf" ] || { _pd=$(diff_asset "$_po") && [ -s "$STAGE/$_pd" ] && _pf=$STAGE/$_pd; }
        _pv=$(untar -xzOf "$_pf" ./etc/mu300/image-version 2>/dev/null | head -n1)
        [ "$_pv" = "$_pt" ] && continue
        echo "$(rootfs_asset "$_po") says it is ${_pv:-no release at all}, not $_pt: not installed" >&2
        return 1
    done
    return 0
}
# boot_downgrade_ok TAG: the same for a kernel or a boot image taken alone (boot, kernel)
boot_downgrade_ok() {
    [ -z "${MU300_ALLOW_DOWNGRADE:-}" ] || return 0
    for _bi in "$(installed_version)" "$(cat "$BOOTDIR/installed.tag" 2>/dev/null)"; do
        newer "$_bi" "$1" || continue
        echo "$1 is older than what is installed ($_bi): its kernel is taken only with MU300_ALLOW_DOWNGRADE=1" >&2
        return 1
    done
    return 0
}

# -- an update from a file or a directory, for a device that is not online (MU300_FROM, set by apply --from).
# A directory holds a release's files as they are published, with their SHA256SUMS (and SHA256SUMS.sig). A file is
# a Magisk zip of the release (mu300-magisk-TAG-SYSTEM-kKERNEL.zip, tools/make-magisk-zips.sh): one system and one
# kernel, with mu300/manifest naming them and their hashes, and - from the release that brought this - the release's
# SHA256SUMS and its signature. Nothing of a zip is unpacked to a path it names: each member is read to a pipe by a
# name this code made.
zip_p() {  # zip_p ZIP MEMBER: the member on stdout
    # (OpenWrt has no unzip, and its own busybox no such applet: the static busybox of the image has)
    _zb=${MU300_BIN:-/opt/mu300/bin}/busybox
    if have unzip; then unzip -p "$1" "$2"
    elif [ -x "$_zb" ]; then "$_zb" unzip -p "$1" "$2"
    else busybox unzip -p "$1" "$2"; fi 2>/dev/null
}
man_val() { sed -n "s/^$2=//p" "$1" | head -n1 | tr -d '\r'; }
# from_open: read the source once per run. FROM_KIND zip|dir, FROM_TAG, and for a zip FROM_OS, FROM_UBUNTU,
# FROM_KERNEL, FROM_ROOTFS, FROM_KASSET; $FROM_TMP/SHA256SUMS (and .sig) are its checksums. Status 1 with a reason in
# FROM_WHY when it is not a release: not-found, not-release, no-tag. FROM_TMP is in the staging directory, which
# the end of an update removes and only a run that holds the lock writes; inspect, which holds none, brings a
# directory of its own (FROM_SCRATCH).
FROM_KIND=
from_open() {
    [ -z "$FROM_KIND" ] || return 0
    FROM_WHY=not-found
    [ -e "$MU300_FROM" ] && [ ! -L "$MU300_FROM" ] || return 1
    [ -n "${FROM_SCRATCH:-}" ] || stage_private || return 1
    FROM_TMP=${FROM_SCRATCH:-$STAGE/.from}
    rm -rf "${FROM_TMP:?}"
    ( umask 077; mkdir -p "$FROM_TMP" ) || return 1
    # (what this run writes of the source, here and into the staging directory, is root's alone: the umask of the
    # run itself stays as it is - the new system's directories are made under it)
    _fu=$(umask); umask 077; from_read; _fr=$?; umask "$_fu"
    return $_fr
}
from_read() {
    FROM_WHY=not-release
    FROM_OS= FROM_UBUNTU= FROM_KERNEL= FROM_ROOTFS= FROM_KASSET=
    if [ -d "$MU300_FROM" ]; then
        [ -f "$MU300_FROM/SHA256SUMS" ] && [ ! -L "$MU300_FROM/SHA256SUMS" ] || return 1
        cat "$MU300_FROM/SHA256SUMS" > "$FROM_TMP/SHA256SUMS"
        [ ! -f "$MU300_FROM/SHA256SUMS.sig" ] || [ -L "$MU300_FROM/SHA256SUMS.sig" ] || cat "$MU300_FROM/SHA256SUMS.sig" > "$FROM_TMP/SHA256SUMS.sig"
        # which release: said (MU300_RELEASE), else what the first root filesystem there says it is
        FROM_TAG=${MU300_RELEASE:-}
        if [ -z "$FROM_TAG" ]; then
            for _fo in $SYSTEMS; do
                [ -f "$MU300_FROM/mu300-$_fo-rootfs.tar.gz" ] || continue
                FROM_TAG=$(untar -xzOf "$MU300_FROM/mu300-$_fo-rootfs.tar.gz" ./etc/mu300/image-version 2>/dev/null | head -n1)
                break
            done
        fi
        tag_ok "$FROM_TAG" || { FROM_WHY=no-tag; return 1; }
        FROM_KIND=dir
        return 0
    fi
    [ -f "$MU300_FROM" ] && [ "$(head -c 2 "$MU300_FROM")" = PK ] || return 1
    zip_p "$MU300_FROM" mu300/manifest > "$FROM_TMP/manifest" && [ -s "$FROM_TMP/manifest" ] || return 1
    FROM_TAG=$(man_val "$FROM_TMP/manifest" TAG)
    FROM_OS=$(man_val "$FROM_TMP/manifest" OS)
    FROM_UBUNTU=$(man_val "$FROM_TMP/manifest" UBUNTU)
    FROM_KERNEL=$(man_val "$FROM_TMP/manifest" KERNEL)
    FROM_ROOTFS=$(man_val "$FROM_TMP/manifest" ROOTFS_ASSET)
    FROM_KASSET=$(man_val "$FROM_TMP/manifest" KERNEL_ASSET)
    # every field is one of the values the release makes, and the file names are the ones those values give
    tag_ok "$FROM_TAG" || return 1
    case $FROM_OS:$FROM_UBUNTU in
        openwrt:|openwrt-luci:) _fr=mu300-$FROM_OS-rootfs.tar.gz ;;
        ubuntu:24.04) _fr=mu300-ubuntu-rootfs.tar.gz ;;
        ubuntu:26.04) _fr=mu300-ubuntu-26.04-rootfs.tar.gz ;;
        *) return 1 ;;
    esac
    # (7.2 is retired, yet the zips and directories of the releases that had it are still read: from_fits says why
    # one does not fit)
    case $FROM_KERNEL in 5.4) _fk=mu300-kernel.tar.gz ;; 6.18|7.2|7.3) _fk=mu300-kernel-$FROM_KERNEL.tar.gz ;; *) return 1 ;; esac
    [ "$FROM_ROOTFS" = "$_fr" ] && [ "$FROM_KASSET" = "$_fk" ] || return 1
    # the release's own SHA256SUMS where the zip has it (it is what the signature covers); else the two hashes of
    # the manifest, which say only that the file is whole
    if zip_p "$MU300_FROM" mu300/SHA256SUMS > "$FROM_TMP/SHA256SUMS" && [ -s "$FROM_TMP/SHA256SUMS" ]; then
        zip_p "$MU300_FROM" mu300/SHA256SUMS.sig > "$FROM_TMP/SHA256SUMS.sig" || :
        [ -s "$FROM_TMP/SHA256SUMS.sig" ] || rm -f "${FROM_TMP:?}/SHA256SUMS.sig"
    else
        _f1=$(man_val "$FROM_TMP/manifest" SHA256_ROOTFS); _f2=$(man_val "$FROM_TMP/manifest" SHA256_KERNEL)
        sha_ok "$_f1" && sha_ok "$_f2" || return 1
        printf '%s  %s\n%s  %s\n' "$_f1" "$FROM_ROOTFS" "$_f2" "$FROM_KASSET" > "$FROM_TMP/SHA256SUMS"
    fi
    FROM_KIND=zip
}
from_close() {
    [ -z "${FROM_TMP:-}" ] || rm -rf "${FROM_TMP:?}"
    [ -z "${FROM_SCRATCH:-}" ] || rm -rf "${FROM_SCRATCH:?}"
    FROM_TMP=; FROM_KIND=; FROM_SCRATCH=
}
# from_member NAME: the file NAME of the source on stdout
from_member() {
    if [ "$FROM_KIND" = dir ]; then
        [ -f "$MU300_FROM/$1" ] && [ ! -L "$MU300_FROM/$1" ] && cat "$MU300_FROM/$1"
    else
        case $1 in mu300-update) zip_p "$MU300_FROM" mu300/mu300-update ;; *) zip_p "$MU300_FROM" "payload/$1" ;; esac
    fi
}
# from_fits: is the source for this device and what is installed? Else the reason in FROM_WHY: system-missing (a
# zip's system is not on this device; a directory has no system that is), ubuntu-release (the other Ubuntu), kernel
# (a zip's kernel is not the one this device uses: the system and the kernel of one release go together), device
# (its kernel does not run on this model).
from_fits() {
    if [ "$FROM_KIND" = dir ]; then
        for _fo in $(installed_systems); do
            [ -z "$(sums_want "$FROM_TMP/SHA256SUMS" "$(rootfs_asset "$_fo")")" ] || return 0
        done
        FROM_WHY=system-missing; return 1
    fi
    [ -d "$DISK/$FROM_OS" ] || { FROM_WHY=system-missing; return 1; }
    [ "$FROM_OS" != ubuntu ] || [ "$(rootfs_asset ubuntu)" = "$FROM_ROOTFS" ] || { FROM_WHY=ubuntu-release; return 1; }
    [ "$FROM_KERNEL" = "$(kernel_choice)" ] || { FROM_WHY=kernel; return 1; }
    _fd=$(from_member "$FROM_KASSET" | untar -xzOf - ./devices 2>/dev/null)
    _fd=$(echo $_fd)
    # (a bundle from before ./devices is the F50's, as bundle_runs_here has it)
    if [ -z "$_fd" ]; then [ "$(this_device)" = f50 ] || { FROM_WHY=device; return 1; }
    else case " $_fd " in *" $(this_device) "*) ;; *) FROM_WHY=device; return 1 ;; esac; fi
}
# from_installed: the release the source would replace (a zip: its system's; a directory: the image's)
from_installed() {
    if [ "$FROM_KIND" = zip ]; then cat "$DISK/$FROM_OS$VERSION_FILE" 2>/dev/null || echo unknown; else installed_version; fi
}
# apply_options ARG...: the options of an offline source taken out of apply's arguments; what is left (systems,
# --no-reinstall) in APPLY_ARGS
apply_options() {
    APPLY_ARGS= _ao=
    # (said on the command line of this run, never inherited - but kept by a run continued with the release's updater)
    [ -n "${MU300_SELF_UPDATED:-}" ] || MU300_FROM_SHA=
    for _aa in "$@"; do
        if [ -n "$_ao" ]; then MU300_FROM=$_aa; _ao=; continue; fi
        case $_aa in
            --from) _ao=1 ;;
            --unsigned) MU300_ALLOW_UNSIGNED=1; export MU300_ALLOW_UNSIGNED ;;
            --downgrade) MU300_ALLOW_DOWNGRADE=1; export MU300_ALLOW_DOWNGRADE ;;
            # (--sha256=HASH: the file is the one with this SHA-256 - the one inspect was shown for - or nothing)
            --sha256=*) MU300_FROM_SHA=${_aa#--sha256=}; sha_ok "$MU300_FROM_SHA" || die "usage: mu300-update apply --from FILE --sha256=HASH" ;;
            # (a system's name or an option: one plain word, so that the list can be passed on as words)
            ''|*[!A-Za-z0-9._-]*) die "unknown system '$_aa'" ;;
            *) APPLY_ARGS="$APPLY_ARGS $_aa" ;;
        esac
    done
    [ -z "$_ao" ] || die "usage: mu300-update apply --from FILE|DIR [--unsigned] [--downgrade]"
}
# from_begin: apply --from, before anything else: the source is a release for this device, signed (or taken with
# --unsigned), and not older than what is installed (or taken with --downgrade). Then apply runs as it always
# does, with fetch_verified reading from the source.
from_begin() {
    if [ -n "${MU300_FROM_SHA:-}" ]; then
        [ -f "$MU300_FROM" ] && [ ! -L "$MU300_FROM" ] && [ "$(sha_of "$MU300_FROM")" = "$MU300_FROM_SHA" ] ||
            die "$MU300_FROM is not the file that was looked at (another SHA-256): nothing was changed"
        export MU300_FROM_SHA
    fi
    from_open || { _fw=$FROM_WHY; from_close
        die "$MU300_FROM is not a release of this project ($_fw): a Magisk zip of a release (mu300-magisk-TAG-SYSTEM-kKERNEL.zip), or a directory with the release's files and their SHA256SUMS"; }
    from_fits || {
        case $FROM_WHY in
            system-missing) _fw="its system${FROM_OS:+ ($FROM_OS)} is not installed on this device" ;;
            ubuntu-release) _fw="it is Ubuntu $FROM_UBUNTU, and this device has the other release" ;;
            kernel) if kernel_retired "$FROM_KERNEL" >/dev/null; then
                        _fw="it carries kernel $FROM_KERNEL, which is retired, and this device uses $(kernel_choice): take the zip for k$(kernel_choice) of a newer release"
                    else
                        _fw="it carries kernel $FROM_KERNEL, and this device uses $(kernel_choice): take the zip for k$(kernel_choice), or change the kernel first"
                    fi ;;
            *) _fw="its kernel does not run on the $(this_device)" ;;
        esac
        from_close; die "$MU300_FROM is not for this device: $_fw. Nothing was changed"
    }
    if newer "$(from_installed)" "$FROM_TAG" && [ -z "${MU300_ALLOW_DOWNGRADE:-}" ]; then
        _fi=$(from_installed); from_close
        die "$MU300_FROM is $FROM_TAG, older than what is installed ($_fi): not used (--downgrade takes it anyway)"
    fi
    # the checksums are judged once and pinned by their hash: every file is then checked against those very bytes
    FROM_PIN=$(sha_of "$FROM_TMP/SHA256SUMS") || { from_close; die "cannot read the checksums of $MU300_FROM"; }
    sums_verdict "$FROM_TAG" "$(sig_state "$FROM_TMP/SHA256SUMS" "$FROM_TMP/SHA256SUMS.sig")" "$MU300_FROM" "$FROM_TMP/SHA256SUMS" ||
        { from_close; die "nothing was changed (--unsigned takes a file that is not signed; never one whose signature is wrong)"; }
    FROM_ONLY=$FROM_OS
    MU300_RELEASE=$FROM_TAG
    export MU300_FROM MU300_RELEASE
    [ -z "${MU300_ALLOW_UNSIGNED:-}" ] || export MU300_ALLOW_UNSIGNED
    [ -z "${MU300_ALLOW_DOWNGRADE:-}" ] || export MU300_ALLOW_DOWNGRADE
}
# from_verified TAG ASSET: fetch_verified's work from the source. 2 when the source does not have the file (as a
# release that does not carry it), 1 when what it has does not match.
from_verified() {
    # only what from_begin judged: the checksums it pinned, read again from nowhere else
    [ -n "${FROM_PIN:-}" ] && [ "$FROM_KIND" != "" ] || { echo "$MU300_FROM was not checked (from_begin): nothing is taken from it" >&2; return 1; }
    stage_private || return 1
    ( umask 077; rm -f "${STAGE:?}/SHA256SUMS"; cat "$FROM_TMP/SHA256SUMS" > "$STAGE/SHA256SUMS"; echo "$1" > "$STAGE/SHA256SUMS.tag" )
    [ "$(sha_of "$STAGE/SHA256SUMS")" = "$FROM_PIN" ] ||
        { echo "the checksums of $MU300_FROM changed after they were checked: nothing more is taken from it" >&2; return 1; }
    want=$(sums_want "$STAGE/SHA256SUMS" "$2")
    [ -n "$want" ] || { echo "$2 is not part of $MU300_FROM" >&2; return 2; }
    [ -s "$STAGE/$2" ] && [ "$(sha_of "$STAGE/$2")" = "$want" ] && return 0
    rm -f "${STAGE:?}/${2:?}"
    ( umask 077; from_member "$2" > "$STAGE/$2" ) && [ -s "$STAGE/$2" ] || { rm -f "${STAGE:?}/${2:?}"; echo "$2 is not in $MU300_FROM" >&2; return 2; }
    [ "$(sha_of "$STAGE/$2")" = "$want" ] && return 0
    rm -f "${STAGE:?}/${2:?}"
    echo "$2 in $MU300_FROM does not match its checksum" >&2
    return 1
}
# from_handover FILE: may apply continue with the release's own updater FILE? Always when online; from a file only
# with one that knows what a file is (an older one would go to GitHub for the release instead). What this run read of
# the source is let go of: the next one reads it again.
from_handover() {
    [ -n "${MU300_FROM:-}" ] || return 0
    grep -q '^from_verified() {' "$1" 2>/dev/null || return 1
    from_close; FROM_PIN=
}

# inspect FILE|DIR: what the source is, as JSON, for a page to show before anything is applied
inspect_json() {
    MU300_FROM=$1
    [ -n "$MU300_FROM" ] || { echo '{"ok":0,"why":"not-found"}'; return 1; }
    FROM_SCRATCH=$(mktemp -d 2>/dev/null) || { echo '{"ok":0,"why":"not-found"}'; return 1; }
    if ! from_open; then printf '{"ok":0,"why":"%s"}\n' "$FROM_WHY"; from_close; return 1; fi
    _is=; [ ! -f "$MU300_FROM" ] || _is=$(sha_of "$MU300_FROM")
    _iz=; [ ! -f "$MU300_FROM" ] || _iz=$(fsize "$MU300_FROM")
    _if=1 _iw=
    from_fits || { _if=0; _iw=$FROM_WHY; }
    # the files it would install are whole: each one the source has is hashed against its checksum
    if [ "$FROM_KIND" = zip ]; then _il="$FROM_ROOTFS $FROM_KASSET"
    else _il="$(for _fo in $(installed_systems); do rootfs_asset "$_fo"; done) $(kernel_asset)"; fi
    for _ia in $_il; do
        _iwant=$(sums_want "$FROM_TMP/SHA256SUMS" "$_ia")
        [ -n "$_iwant" ] || { [ "$FROM_KIND" = dir ] && continue; _if=0; _iw=checksum; break; }
        [ "$FROM_KIND" != dir ] || [ -f "$MU300_FROM/$_ia" ] || continue
        _ihave=$(from_member "$_ia" | sha256sum | cut -d' ' -f1)
        [ "$_ihave" = "$_iwant" ] || { _if=0; _iw=checksum; break; }
    done
    _ig=$(sig_state "$FROM_TMP/SHA256SUMS" "$FROM_TMP/SHA256SUMS.sig")
    # (signed checksums must be this release's own: what a signature says of another release, or of none, is
    # nothing - "bad" for the page, as sums_verdict refuses it)
    _it=$(sums_want "$FROM_TMP/SHA256SUMS" mu300-release)
    if [ -n "$_it" ] && [ "$_it" != "$(tag_sha "$FROM_TAG")" ]; then _ig=bad
    elif [ "$_ig" = valid ] && [ -z "$_it" ]; then _ig=bad
    elif [ "$_ig" = badkey ]; then _ig=bad; fi
    [ "$_ig" != bad ] || { _if=0; _iw=signature; }
    _ii=$(from_installed)
    printf '{"ok":1,"kind":"%s","sha256":%s,"size":%s,"tag":"%s","system":%s,"ubuntu":%s,"kernel":%s,"signature":"%s","installed":%s,"downgrade":%d,"same":%d,"fits":%d,"why":%s}\n' \
        "$FROM_KIND" "$(jstr "$_is")" "$(jnum "$_iz")" "$(jv "$FROM_TAG")" "$(jstr "$FROM_OS")" "$(jstr "$FROM_UBUNTU")" "$(jstr "$FROM_KERNEL")" \
        "$_ig" "$(jstr "$_ii")" "$(newer "$_ii" "$FROM_TAG" && echo 1 || echo 0)" "$([ "$_ii" = "$FROM_TAG" ] && echo 1 || echo 0)" "$_if" "$(jstr "$_iw")"
    from_close
}

# lock_holder: the pid of the mu300-update that holds the lock now, or nothing. Only looks (the lock itself is
# never tried: a probe that held it for a moment could turn a real run away).
lock_holder() {
    for _lf in "$LOCK/lock" "$LOCK/held/pid"; do
        [ -f "$_lf" ] && [ ! -L "$_lf" ] || continue
        _lh=$(lock_pid "$_lf")
        [ -n "$_lh" ] && [ "$_lh" != "$$" ] && update_alive "$_lh" || continue
        # (the pid may be another program's by now, or a mu300-update that only looks)
        case " $({ tr '\0' ' ' < "/proc/$_lh/cmdline"; } 2>/dev/null) " in
            *" status "*|*" releases "*|*" inspect "*|*" notice "*|*" check "*|*" version "*) continue ;;
        esac
        echo "$_lh"; return 0
    done
}
# size_kb DIR: its size in KiB, only when asked for (status --sizes: a whole system takes seconds to add up)
size_kb() { if [ -n "$STATUS_SIZES" ]; then jnum "$(du -sk "$1" 2>/dev/null | awk '{print $1}')"; else printf null; fi; }
status_json() {
    STATUS_SIZES=; [ "${1:-}" != --sizes ] || STATUS_SIZES=1
    _run=$(running_os)
    printf '{"ok":1,"device":"%s","installed":"%s","running":"%s","restart_pending":%d,' "$(jv "$(this_device 2>/dev/null)")" \
        "$(jv "$(installed_version)")" "$(jv "$_run")" "$(is_root "$DISK/$_run.old" || is_root "$DISK/$_run.broken" && echo 1 || echo 0)"
    printf '"systems":['
    _sep=
    for _os in $(installed_systems); do
        printf '%s{"name":"%s","release":"%s","ubuntu":%s,"since":%s,"previous":' "$_sep" "$_os" \
            "$(jv "$(cat "$DISK/$_os$VERSION_FILE" 2>/dev/null || echo unknown)")" \
            "$([ "$_os" = ubuntu ] && jstr "$(sed -n 's/^VERSION_ID="\(.*\)"/\1/p' "$DISK/ubuntu/etc/os-release" 2>/dev/null)" || printf null)" \
            "$(mtime "$DISK/$_os$VERSION_FILE")"
        if [ -d "$DISK/$_os.old" ]; then
            printf '{"release":"%s","kb":%s,"running":%d}' "$(jv "$(cat "$DISK/$_os.old$VERSION_FILE" 2>/dev/null || echo unknown)")" \
                "$(size_kb "$DISK/$_os.old")" "$(is_root "$DISK/$_os.old" && echo 1 || echo 0)"
        else printf null; fi
        printf '}'
        _sep=,
    done
    printf '],"kernel":{"running":"%s","choice":"%s","choices":[' "$(jv "$(uname -r)")" "$(kernel_choice)"
    _sep=
    for _k in $KERNELS; do
        # (the one refusal known before the download: Ubuntu 26.04 does not run on 5.4, see kernel_cmd)
        _why=; [ "$_k" != 5.4 ] || [ "$(ubuntu_release)" != 26.04 ] || _why=ubuntu-26.04
        printf '%s{"name":"%s","ok":%d,"why":%s}' "$_sep" "$_k" "$([ -z "$_why" ] && echo 1 || echo 0)" "$(jstr "$_why")"
        _sep=,
    done
    printf '],"boot":%s,"boot_kernel":%s,"slot":"%s","previous":' "$(jstr "$(cat "$BOOTDIR/installed.tag" 2>/dev/null)")" \
        "$(jstr "$(cat "$BOOTDIR/installed.kernel" 2>/dev/null)")" "$(linux_slot)"
    if [ -s "$BOOTDIR/prev.body" ]; then
        _ps=$(cat "$BOOTDIR/prev.slot" 2>/dev/null || echo b)
        printf '{"release":%s,"kernel":%s,"since":%s,"usable":%d}' "$(jstr "$(cat "$BOOTDIR/prev.tag" 2>/dev/null)")" \
            "$(jstr "$(cat "$BOOTDIR/prev.kernel" 2>/dev/null)")" "$(mtime "$BOOTDIR/prev.body")" "$([ "$_ps" = "$(linux_slot)" ] && echo 1 || echo 0)"
    else printf null; fi
    # the default boot, and how many boots in a row may fail before Android takes over (mu300-next-boot)
    _db=$(cat "${MU300_DEFAULT_BOOT:-/etc/mu300/default-boot}" 2>/dev/null); [ "$_db" = linux ] || _db=android
    _at=$(cat "$DISK/.mu300/boot-attempts" 2>/dev/null); case $_at in [1-6]) ;; *) _at=5 ;; esac
    printf '},"boot_default":"%s","boot_attempts":%s,"boot_locked":%d,' "$_db" "$_at" "$([ -f "$DISK/.mu300/boot-lock" ] && echo 1 || echo 0)"
    _n=$(echo $(installed_systems) | wc -w | tr -d ' ')
    # (with --sizes also what the carry block copies: for one system the largest of them, for all of them the sum)
    _c1=0 _ca=0
    if [ -n "$STATUS_SIZES" ]; then
        for _os in $(installed_systems); do
            _c=$(carry_need "$_os"); _ca=$((_ca + _c)); [ "$_c" -le "$_c1" ] || _c1=$_c
        done
    fi
    printf '"disk":{"free_kb":%s,"total_kb":%s,"need_one_kb":%s,"need_all_kb":%s},' "$(jnum "$(df -Pk "$DISK" 2>/dev/null | awk 'NR==2 {print $4}')")" \
        "$(jnum "$(df -Pk "$DISK" 2>/dev/null | awk 'NR==2 {print $2}')")" "$(space_needed 1 "$_c1")" "$(space_needed "$_n" "$_ca")"
    _lh=$(lock_holder)
    printf '"lock":{"held":%d,"pid":%s,"command":%s},' "$([ -n "$_lh" ] && echo 1 || echo 0)" "$(jnum "$_lh")" \
        "$([ -n "$_lh" ] && jstr "$({ tr '\0' ' ' < "/proc/$_lh/cmdline"; } 2>/dev/null | sed 's/ *$//')" || printf null)"
    # the note of a newer release (notice, at boot and every 6 hours): its tag
    _nt=$(sed -n 's/^mu300-linux \(v[0-9.]*\) is out .*/\1/p' "$NOTICE" 2>/dev/null | head -n1)
    tag_ok "$_nt" || _nt=
    _vt=none; if have usign; then _vt=usign; elif have openssl; then _vt=openssl; fi
    printf '"notice":%s,"signing":{"key":%d,"tool":"%s"},"source":%s}\n' "$(jstr "$_nt")" "$([ "$(key_state)" = none ] && echo 0 || echo 1)" "$_vt" "$(source_json)"
}

# releases: the newest release, and the newest pre-release when it is newer (never offered by itself: the page
# asks). GitHub's list is read line by line - one "key": value a line once every ," and {" is given a line of its
# own, which the escaped quotes inside a release's notes never are - so no JSON tool is needed (OpenWrt has
# jsonfilter, Ubuntu has none). What this device would download for each: the root filesystem of every system
# that is not that release yet, the kernel of its choice, the installed extras, the updater.
# release_json TAG: one release of $RELEASES (lines "R TAG PRE DRAFT PUBLISHED TITLE", then "A TAG SIZE NAME" for
# each of its files) as JSON
release_json() {
    _rl=$(printf '%s\n' "$RELEASES" | awk -v t="$1" '$1 == "R" && $2 == t { print; exit }')
    _want="$(kernel_asset) mu300-update"
    _ns=0 _nl= _nd=0
    for _os in $(installed_systems); do
        [ "$(cat "$DISK/$_os$VERSION_FILE" 2>/dev/null)" = "$1" ] && continue
        # (the diff from the installed image where the release has one: what apply downloads, the diff block)
        _ra=$(rootfs_asset "$_os")
        if [ "${MU300_DIFF:-1}" != 0 ] && _rd=$(diff_asset "$_os") &&
            printf '%s\n' "$RELEASES" | awk -v t="$1" -v f="$_rd" '$1 == "A" && $2 == t && $4 == f { x = 1 } END { exit !x }'; then
            _ra=$_rd _nd=$((_nd + 1))
        fi
        _want="$_want $_ra"; _ns=$((_ns + 1)); _nl="$_nl $_os"
    done
    for _x in $(extras_to_fetch "$1"); do _want="$_want $(extra_asset "$_x")"; done
    printf '{"tag":"%s","title":%s,"published":%s,"url":"https://github.com/%s/releases/tag/%s","signed":%d,"systems":%d,"diffs":%d,"need_kb":%s,"files":[' \
        "$1" "$(jstr "$(printf '%s\n' "$_rl" | cut -d' ' -f6-)")" "$(jstr "$(printf '%s\n' "$_rl" | awk '{print $5}' | cut -c1-10)")" \
        "$(jv "$REPO")" "$1" "$(printf '%s\n' "$RELEASES" | awk -v t="$1" '$1 == "A" && $2 == t && $4 == "SHA256SUMS.sig" { f = 1 } END { print f + 0 }')" \
        "$_ns" "$_nd" "$(space_needed "$_ns" "$(carry_need $_nl)")"
    _sep= _tot=0
    for _f in $_want; do
        _sz=$(printf '%s\n' "$RELEASES" | awk -v t="$1" -v f="$_f" '$1 == "A" && $2 == t && $4 == f { print $3; exit }')
        case $_sz in ''|*[!0-9]*) continue ;; esac
        printf '%s{"name":"%s","size":%s}' "$_sep" "$(jv "$_f")" "$_sz"
        _sep=,; _tot=$((_tot + _sz))
    done
    printf '],"download":%s}' "$_tot"
}
releases_json() {
    _latest=$(latest_release)
    # (no answer to the first question: offline, without waiting for a second one - on the U30 Air without a route
    # each question took 24 s)
    tag_ok "$_latest" || { echo '{"ok":0,"why":"offline"}'; return 1; }
    _all=$(fetch_stdout "${MU300_API_URL:-https://api.github.com/repos/$REPO}/releases?per_page=10") || _all=
    if ! tag_ok "$_latest" || [ -z "$_all" ]; then echo '{"ok":0,"why":"offline"}'; return 1; fi
    RELEASES=$(printf '%s\n' "$_all" | awk '
        function val(s) { sub(/^[^:]*:[ \t]*/, "", s); sub(/[ \t]*,?[ \t\r]*$/, "", s); gsub(/^"|"$/, "", s); return s }
        function flush() { if (tag != "") { print "R", tag, pre, draft, pub, title; printf "%s", files } tag = ""; files = "" }
        function line(s) {
            if (s ~ /^[ \t]*"tag_name":/) { flush(); tag = val(s); pre = "false"; draft = "false"; pub = "-"; title = ""; inas = 0; an = ""; return }
            if (tag == "") return
            if (s ~ /^[ \t]*"assets":/) { inas = 1; return }
            if (s ~ /^[ \t]*"tarball_url":/) { inas = 0; return }
            if (s ~ /^[ \t]*"name":/) { if (inas) an = val(s); else if (title == "") title = val(s); return }
            if (inas && an != "" && s ~ /^[ \t]*"size":/) { files = files "A " tag " " val(s) " " an "\n"; an = ""; return }
            if (inas) return
            if (s ~ /^[ \t]*"prerelease":/) pre = val(s)
            else if (s ~ /^[ \t]*"draft":/) draft = val(s)
            else if (s ~ /^[ \t]*"published_at":/) pub = val(s)
        }
        { gsub(/,"/, ",\n\""); gsub(/\{"/, "{\n\""); n = split($0, L, "\n"); for (i = 1; i <= n; i++) line(L[i]) }
        END { flush() }')
    _beta=
    for _bt in $(printf '%s\n' "$RELEASES" | awk '$1 == "R" && $3 == "true" && $4 == "false" { print $2 }'); do
        tag_ok "$_bt" && { [ -z "$_beta" ] || newer "$_bt" "$_beta"; } && _beta=$_bt
    done
    newer "$_beta" "$_latest" || _beta=
    printf '{"ok":1,"installed":"%s","boot":%s,"latest":%s,"beta":%s}\n' "$(jv "$(installed_version)")" \
        "$(jstr "$(cat "$BOOTDIR/installed.tag" 2>/dev/null)")" "$(release_json "$_latest")" \
        "$([ -n "$_beta" ] && release_json "$_beta" || printf null)"
}
# progress WHAT: a line for whoever follows this run (MU300_PROGRESS, a file): "file NAME" as a download starts
progress() { [ -z "${MU300_PROGRESS:-}" ] || printf '%s\n' "$*" >> "$MU300_PROGRESS" 2>/dev/null || :; }
# ---- for a panel: end

# ---- the release source (mu300-update source): the address the release files come from, set from the command line
# What /etc/mu300/update-source names, for a person and for the panel's field: the file source_conf reads, written
# through the same checks it applies (a plain http(s) URL; root's own regular file; no link), so a value this writes
# is a value the next run takes. Only MU300_DOWNLOAD_URL is written here - the whole-base MU300_RELEASE_URL and the
# API address stay whatever they were.
# source_file_value NAME: what the source file names for NAME, or nothing - the same value source_conf would take
# (a plain http(s) URL in root's own file), read the same way
source_file_value() {
    [ -f "$SOURCE_CONF" ] && [ ! -L "$SOURCE_CONF" ] || return 0
    # the same rule source_conf applies: a file others can write is not one this device takes a source from
    case $(ls -ln "$SOURCE_CONF" 2>/dev/null) in -????-??-?*) ;; *) return 0 ;; esac
    [ -O "$SOURCE_CONF" ] || return 0
    # (the first line, as source_conf takes it: a file with two lines of this name is hand-edited, and the reader
    #  and the writer have to agree on which one is in force)
    _fv=$(sed -n "s/^[[:space:]]*$1=//p" "$SOURCE_CONF" 2>/dev/null | head -n1)
    printf '%s\n' "$_fv" | grep -Eqx 'https?://[A-Za-z0-9._:/-]{1,200}' || return 0
    printf '%s\n' "$_fv"
}
# source_state NAME: where NAME's value comes from, and the value, as "origin value" - env (this process's
# environment won, as source_conf lets it), file (the source file), or github (neither names one)
source_state() {
    case $1 in
        MU300_DOWNLOAD_URL)
            if [ -n "${MU300_RELEASE_URL:-}" ]; then printf 'env %s\n' "$MU300_RELEASE_URL"; return; fi
            if [ -n "$SOURCE_ENV_DL" ]; then printf 'env %s\n' "$SOURCE_ENV_DL"; return; fi ;;
        MU300_API_URL)
            if [ -n "$SOURCE_ENV_API" ]; then printf 'env %s\n' "$SOURCE_ENV_API"; return; fi ;;
    esac
    _sv=$(source_file_value "$1")
    if [ -n "$_sv" ]; then printf 'file %s\n' "$_sv"; else printf 'github\n'; fi
}
# source_json: the release source of this run, for a panel (status_json). Only the file and GitHub can be in force
# there: the adapter clears every environment variable that names a source before it runs the updater.
source_json() {
    _st=$(source_state MU300_DOWNLOAD_URL); _so=${_st%% *}; _sv=${_st#* }
    case $_so in
        github) printf '{"files":null,"from":"github"}\n' ;;
        *) printf '{"files":%s,"from":"%s"}\n' "$(jstr "$_sv")" "$_so" ;;
    esac
}
source_show() {
    _st=$(source_state MU300_DOWNLOAD_URL); _so=${_st%% *}; _sv=${_st#* }
    case $_so in
        env) if [ -n "${MU300_RELEASE_URL:-}" ]; then
                 printf 'release files  %s  (MU300_RELEASE_URL: the whole base, the release tag is not added)\n' "$_sv"
             else printf 'release files  %s  (environment)\n' "$_sv"; fi ;;
        file) printf 'release files  %s  (%s)\n' "$_sv" "$SOURCE_CONF" ;;
        *) printf 'release files  %s  (default)\n' "https://github.com/$REPO/releases/download" ;;
    esac
    _st=$(source_state MU300_API_URL); _so=${_st%% *}; _sv=${_st#* }
    case $_so in
        env) printf 'release list   %s  (environment)\n' "$_sv" ;;
        file) printf 'release list   %s  (%s)\n' "$_sv" "$SOURCE_CONF" ;;
        *) printf 'release list   %s  (default)\n' "https://api.github.com/repos/$REPO" ;;
    esac
}
# source_dir_ok: where the file goes - made if needed, and never through a link, a directory of somebody else's, or
# one others can write (a directory others can write lets them put their own file where this one is written)
source_dir_ok() {
    _dd=${SOURCE_CONF%/*}
    [ ! -L "$SOURCE_CONF" ] || { echo "$SOURCE_CONF is a link: nothing was changed" >&2; return 1; }
    [ -d "$_dd" ] || mkdir -p "$_dd" 2>/dev/null || { echo "$_dd cannot be made" >&2; return 1; }
    case $(ls -ldn "$_dd" 2>/dev/null) in
        d????-??-?*) ;;
        *) echo "$_dd is not a directory of ours, or is writable by others: nothing was changed" >&2; return 1 ;;
    esac
    [ -O "$_dd" ] || { echo "$_dd is not ours: nothing was changed" >&2; return 1; }
    [ ! -e "$SOURCE_CONF" ] || { [ -f "$SOURCE_CONF" ] && [ ! -L "$SOURCE_CONF" ] && [ -O "$SOURCE_CONF" ]; } ||
        { echo "$SOURCE_CONF is not ours: nothing was changed" >&2; return 1; }
}
# source_put TEXT: TEXT (or nothing, to take the line out) becomes the MU300_DOWNLOAD_URL line, everything else kept
source_put() {
    source_dir_ok || return 1
    _pt=${SOURCE_CONF}.new
    # root's own from the first byte: the redirection would otherwise create it 0644 (umask 022, which is what the
    # adapter's run_cmd uses) and leave a readable copy of the address behind if this process is killed before the mv
    ( umask 077; { [ ! -f "$SOURCE_CONF" ] || grep -v '^[[:space:]]*MU300_DOWNLOAD_URL=' "$SOURCE_CONF" || :
                   [ -z "${1:-}" ] || printf 'MU300_DOWNLOAD_URL=%s\n' "$1"; } > "$_pt" 2>/dev/null || : )
    chmod 600 "$_pt" && mv "$_pt" "$SOURCE_CONF" || { rm -f "$_pt"; echo "could not write $SOURCE_CONF" >&2; return 1; }
    # nothing left in it but blank lines and comments: the file itself goes
    [ -n "${1:-}" ] || grep -qv '^[[:space:]]*\(#\|$\)' "$SOURCE_CONF" || rm -f "$SOURCE_CONF"
}
source_cmd() {  # source_cmd [URL|off]: show it, name another one, or take it back out
    case ${1:-} in
        '') [ $# = 0 ] || die "usage: mu300-update source [URL|off]"; source_show ;;
        off) [ $# = 1 ] || die "usage: mu300-update source [URL|off]"; source_put && source_show ;;
        -*) die "usage: mu300-update source [URL|off]" ;;
        *) [ $# = 1 ] || die "usage: mu300-update source [URL|off]"
           printf '%s\n' "$1" | grep -Eqx 'https?://[A-Za-z0-9._:/-]{1,200}' || die "not an http(s) URL: $1"
           source_put "$1" && source_show ;;
    esac
}

# tests/ source this file for its functions only (MU300_BIN, MU300_DISK: a fake device)
[ -z "${MU300_LIB:-}" ] || return 0

# carry OLD NEW OS copy|link: the carry block, as apply_one and the installers run it from the new image (carry_run).
# It changes NEW only, the run that called it holds the lock, and it is root because that run is.
case ${1:-} in
    carry) shift; carry_system "$@"; exit $? ;;
    # delta-room OLD WORK OS [VENDOR]: the installers' count of what an update writes (the delta block); it only reads
    delta-room) shift; delta_room "$@"; exit $? ;;
esac

[ "$(id -u)" = 0 ] || { echo "run as root" >&2; exit 1; }
case ${1:-check} in
    apply|boot|kernel|rollback|rollback-boot|clean|accounts)
        lock_take; trap 'unpack_abort; keepalive_stop; resume_data; lock_drop' EXIT; trap 'exit 130' INT TERM HUP
        modules_settle ;;
esac
source_conf
case ${1:-check} in apply|boot|kernel) keepalive_start ;; esac
case ${1:-check} in
    check) check ;;
    version) version ;;
    # (apply_options: --from FILE|DIR, --unsigned, --downgrade, the offline source; the rest is apply's, as words)
    apply) shift; apply_options "$@"; apply $APPLY_ARGS ;;
    status) shift; status_json "$@" ;;
    releases) mounted_disk; releases_json ;;
    inspect) mounted_disk; inspect_json "${2:-}" ;;
    boot) mounted_disk; t=${MU300_RELEASE:-$(latest_release)}; [ -n "$t" ] || die "could not reach GitHub ($(offline_why))"
          boot_downgrade_ok "$t" || exit 1
          boot_update "$t" || exit 1; rm -rf "$STAGE"; [ -n "${BOOT_CHANGED:-}" ] && { printf '\n'; reboot_goes_to_android || printf 'Reboot to start the new kernel.\n'; } ;;
    rollback) shift; rollback "$@" ;;
    rollback-boot) rollback_boot ;;
    kernel) shift; kernel_cmd "$@" ;;
    accounts) accounts ;;
    clean) clean ;;
    notice) notice ;;
    report) report ;;
    source) shift; source_cmd "$@" ;;
    -h|--help|help) sed -n '2,30s/^# \{0,1\}//p' "$0" ;;
    *) echo "usage: mu300-update check|version|apply [--no-reinstall] [--no-rollback] [ubuntu|openwrt|openwrt-luci ...]|boot|kernel [5.4|6.18|7.3]|rollback [os]|rollback-boot|clean|report|notice|source [URL|off]|status|releases|inspect FILE" >&2; exit 2 ;;
esac
