#!/bin/sh

# We're going to need to remember failures from the *left* side of a pipeline...
# But because we can't have nice things, some devices (hi, Kindle) may use an extremely old busybox build,
# one in which pipefail was not yet implemented,
# (it appeared in busybox 1.16.0, and is contingent on bash compatibility being enabled in ash).

# NOTE: We inherit WITH_PIPEFAIL from the env via OTAManager, because of course old busybox ash versions abort on set -o failures...
#       c.f., https://github.com/koreader/koreader/pull/5844
if [ "${WITH_PIPEFAIL}" = "true" ]; then
    # shellcheck disable=SC3040
    set -o pipefail
fi

# Figure out whether that's a delta or a full download given the number of arguments passed...
if [ $# -lt 7 ]; then
    ZSYNC_MESSAGE="Downloading update data"
else
    ZSYNC_MESSAGE="Computing zsync delta"
fi

# Clear screen before start
./fbink --cls
# Small zsync wrapper so we can print its output while it works...
./fbink -q -y -7 -pmh "${ZSYNC_MESSAGE} . . ."
# Clear any potential leftover from the local OTA tarball creation.
./fbink -q -y -6 -pm ' '

# Launch zsync2, and remember its exit code...
# We'll be piping its output to FBInk in order to print it live, in a smaller font than usual...
# NOTE: This depends on an undocumented FBInk hack (-z) in order to deal with the progress bars (and their CR) sanely.
rc=0

if [ "${WITH_PIPEFAIL}" = "true" ]; then
    # We can use pipefail, let the shell do the heavy lifting for us...
    ./zsync2 "$@" 2>&1 | tee -a ./crash.log | ./fbink -q -z -pm -F scientifica
    rc=$?
else
    # We cannot use pipefail, extreme shell wizardry is required...
    # Pure magic courtesy of https://unix.stackexchange.com/a/70675
    # Much more compact than the stock answer from the Usenet shell FAQ: http://cfajohnson.com/shell/cus-faq-2.html#Q11
    { { { {
        ./zsync2 "$@" 2>&1 3>&- 4>&-
        echo $? >&3
    } | ./fbink -q -z -pm -F scientifica >&4; } 3>&1; } | {
        read -r xs
        exit "${xs}"
    }; } 4>&1

    rc=$?
fi

# And return with zsync's exit code
exit ${rc}
