#!/bin/sh
# Creates the restore point that the failback of RobustOS Pro 2.4.x restores when the router does not boot anymore
# (3 failed boots): /overlay/backup in the format of `rbt-system-mgmt backup create`. Without a backup the failback restores the
# FACTORY image (original USB image: firmware downgrade, configuration lost).
#
#   backup [--target PKG=VERSION]   exit 0: created, or kept because the update to PKG=VERSION has begun already; exit 1: not created
#
# Why our own writer (RobustOS Pro 2.3.x has no rbt-system-mgmt at all, and the vendor tool cannot exclude anything):
#   - same archive as the vendor tool: tar zcpfP - /overlay/work /overlay/upper /overlay/docker /data/boot (absolute names, the whiteouts of
#     the upper layer are stored as 0,0 character devices), /data/boot/uboot0.bin = dump of the boot partition (the restore flashes it back)
#   - info: TYPE RAW COMPRESSED HASH KERNEL_HASH CREATE_TIME and NO MODEL=: the vendor check compares MODEL= with `uci get devcfg.model`, which is
#     empty while router.service is down (exactly when the failback runs), so a backup WITH the line is always refused (T-X part C)
#   - the payload of an offline update (debs, image) and its "update pending" marker are left out: a restore must not restart the update
# It has to be taken BEFORE the update touches anything. The new backup replaces the old one only when it is complete (built in backup.new).
. "$(dirname "$0")/common.sh"

DATAD=${EG_FAILSAFE_DATA:-/data}
NEW=${OVERLAY}/backup.new
CUR=${OVERLAY}/backup
OLD=${OVERLAY}/backup.old
TARGET=""
[ "$1" = "--target" ] && TARGET=$2

fail() {
    log "backup: $1"
    rm -rf "${NEW}" "${DATAD}/boot/uboot0.bin"
    exit 1
}

# One restore point per update: when the target version of the update is installed or unpacked already, the update has begun
# (a retry after a power loss) and the restore point from before is the right one; a new one would hold a half updated system.
if [ -n "${TARGET}" ] && [ -f "${CUR}/info" ]; then
    tpkg=${TARGET%%=*}
    tver=${TARGET#*=}
    if [ "$(dpkg-query -W -f='${Version}' "${tpkg}" 2> /dev/null)" = "${tver}" ]; then
        log "backup: ${TARGET} is installed already, the update has begun: keeping the restore point"
        exit 0
    fi
fi

dpkg_clean || fail "dpkg is not clean, no restore point of a broken system"
[ -d "${OVERLAY}/upper" ] && [ -d "${OVERLAY}/work" ] || fail "no overlay (${OVERLAY}/upper) found"
mkdir -p "${OVERLAY}/docker" "${DATAD}/boot"

RAW=$(du -sm "${OVERLAY}/work" "${OVERLAY}/upper" "${OVERLAY}/docker" "${DATAD}/boot" 2> /dev/null | awk '{s += $1} END {print s + 0}')
FREE=$(df -Pm "${OVERLAY}" | awk 'NR==2 {print $4}')
# the archive now and the extracted restore (RAW) later have to fit next to each other
if [ "${FREE:-0}" -lt $(( RAW * 2 + 256 )) ]; then
    fail "not enough free space: ${RAW} MB of data, ${FREE} MB free"
fi

# the boot partition that is in use: PARTITION_CONFIG bits 3-5 (1 = boot0, 2 = boot1), boot0 if that cannot be read
uboot_dev() {
    if [ -n "${EG_FAILSAFE_UBOOT_DEV}" ]; then echo "${EG_FAILSAFE_UBOOT_DEV}"; return; fi
    for b in /dev/mmcblk*boot0; do
        [ -b "${b}" ] || continue
        disk=${b%boot0}
        if command -v mmc > /dev/null 2>&1; then
            cfg=$(mmc extcsd read "${disk}" 2> /dev/null | sed -n 's/.*PARTITION_CONFIG: \(0x[0-9a-fA-F]*\).*/\1/p')
            if [ -n "${cfg}" ] && [ $(( (cfg >> 3) & 7 )) -eq 2 ]; then echo "${disk}boot1"; return; fi
        fi
        echo "${b}"
        return
    done
}
UB=$(uboot_dev)
[ -n "${UB}" ] || fail "no boot partition found"

rm -rf "${NEW}" "${OLD}"
mkdir -p "${NEW}"
START=$(date +%s)

dd if="${UB}" of="${DATAD}/boot/uboot0.bin" bs=1M 2> /dev/null || fail "dumping ${UB} failed"
[ -s "${DATAD}/boot/uboot0.bin" ] && [ -n "$(head -c 65536 "${DATAD}/boot/uboot0.bin" | tr -d '\000' | head -c 1)" ] || fail "the dump of ${UB} is empty"

# low priority: on a 2.4.x device with 1.5 GB of data this takes minutes
LOWPRIO=""
command -v nice > /dev/null 2>&1 && LOWPRIO="nice -n 19"
command -v ionice > /dev/null 2>&1 && LOWPRIO="${LOWPRIO} ionice -c3"

U=${OVERLAY}/upper
# shellcheck disable=SC2086
${LOWPRIO} tar zcpfP "${NEW}/backup.tar.gz" \
    --exclude="${U}/usr/share/eurogard/offline-update/debs" \
    --exclude="${U}/usr/share/eurogard/offline-update/image.tar" \
    --exclude="${U}/usr/share/eurogard/nodered/image.tar" \
    --exclude="${U}/upload/tempfile" --exclude="${U}/upload/temp.deb" \
    --exclude="${U}/app/eurogard/offline-update/pending" --exclude="${U}/app/eurogard/offline-update/attempts" \
    "${OVERLAY}/work" "${OVERLAY}/upper" "${OVERLAY}/docker" "${DATAD}/boot" 2> "${NEW}/tar.err"
RC=$?
rm -f "${DATAD}/boot/uboot0.bin"
# 1 = "file changed as we read it" (the system is running), more is a real error
[ "${RC}" -le 1 ] || fail "tar failed (rc ${RC}): $(head -c 200 "${NEW}/tar.err" | tr '\n' ' ')"
rm -f "${NEW}/tar.err"
gzip -t "${NEW}/backup.tar.gz" 2> /dev/null || fail "the archive is damaged"

# next to the archive: the kernel for the recovery under U-Boot (as the vendor tool does)
if [ -r "${DATAD}/boot/kernel.img" ]; then
    cp "${DATAD}/boot/kernel.img" "${NEW}/" || fail "copying the kernel failed"
fi
for d in "${DATAD}"/boot/dtbs-*; do
    [ -d "${d}" ] && cp -a "${d}" "${NEW}/" && ln -sfn "$(basename "${d}")" "${NEW}/dtbs"
done

{
    echo "TYPE=backup"
    echo "RAW=${RAW}"
    echo "COMPRESSED=$(du -sm "${NEW}/backup.tar.gz" | cut -f1)"
    echo "HASH=$(sha256sum "${NEW}/backup.tar.gz" | cut -d' ' -f1)"
    [ -r "${NEW}/kernel.img" ] && echo "KERNEL_HASH=$(sha256sum "${NEW}/kernel.img" | cut -d' ' -f1)"
    echo "CREATE_TIME=$(date +%s)"
} > "${NEW}/info"
sync

# only now the old restore point goes away
[ -d "${CUR}" ] && mv "${CUR}" "${OLD}"
mv "${NEW}" "${CUR}" || { [ -d "${OLD}" ] && mv "${OLD}" "${CUR}"; fail "could not put the new restore point in place"; }
rm -rf "${OLD}"
log "backup: created ${CUR} before ${TARGET:-an update} in $(( $(date +%s) - START )) s: ${RAW} MB of data, archive $(du -sm "${CUR}/backup.tar.gz" | cut -f1) MB, boot partition ${UB}"
sync
exit 0
