#!/bin/bash
# Brings everything the activation needs onto the device: the image in the local Docker store and the unpacked
# module tree. This is the part that needs network (or the offline archive), so it runs during the update, while the
# device is online. Activation is local and can be retried at any time.
#   stage          stage the image and the modules
#   stage --check  exit 0 if there is something to do, 1 if the device is already current
. /usr/lib/eurogard/nodered/common.sh

if [ "${1:-}" = "--check" ]; then
    is_current && exit 1
    exit 0
fi

fail() {
    log "stage failed: $1"
    write_result failed "stage: $1"
    : > "${STATE_DIR}/pending-stage"
    exit 1
}

log "stage: version ${PKG_VERSION}, image ${IMAGE_REF}"
write_result staging "preparing image and modules"
: > "${STATE_DIR}/pending-stage"

# Docker daemon (it is not gated by the fair use terms anymore, only the container is)
systemctl start docker.service > /dev/null 2>&1
for i in $(seq 1 60); do
    docker info > /dev/null 2>&1 && break
    sleep 1
done
docker info > /dev/null 2>&1 || fail "Docker daemon is not available"

# Image: already local, from the offline archive, or pulled from the registry.
# USE_REF is what the container is started from; it is IMAGE_REF (pinned by digest) unless the image came from an
# archive: a loaded image carries no registry digest, so it is tagged with the reference without the digest.
USE_REF="${IMAGE_REF}"
if docker image inspect "${IMAGE_REF}" > /dev/null 2>&1; then
    log "image already present"
elif [ -f "${IMAGE_ARCHIVE}" ]; then
    log "loading the image from ${IMAGE_ARCHIVE}"
    LOADED=$(docker load -i "${IMAGE_ARCHIVE}") || fail "docker load failed"
    log "docker: ${LOADED}"
    LOADED_REF=$(echo "${LOADED}" | sed -n 's/^Loaded image\(: \| ID: \)//p' | tail -n 1)
    [ -n "${LOADED_REF}" ] || fail "docker load did not report a loaded image"
    LOADED_ID=$(docker image inspect "${LOADED_REF}" --format '{{.Id}}' 2> /dev/null)
    if [ -z "${LOADED_ID}" ]; then
        # A load that was cut off (power loss) leaves layers without their link file; Docker then cannot use the image
        # ("readlink .../fuse-overlayfs/l: invalid argument"), now and at every later load. Removing the image removes
        # those layers, the second load is clean.
        log "the loaded image is damaged (an earlier load was interrupted?), removing it and loading again"
        docker rmi -f "${LOADED_REF}" 2>&1 | while IFS= read -r line; do log "docker: ${line}"; done
        LOADED=$(docker load -i "${IMAGE_ARCHIVE}") || fail "docker load failed (second try)"
        log "docker: ${LOADED}"
        LOADED_REF=$(echo "${LOADED}" | sed -n 's/^Loaded image\(: \| ID: \)//p' | tail -n 1)
        [ -n "${LOADED_REF}" ] || fail "docker load did not report a loaded image"
        LOADED_ID=$(docker image inspect "${LOADED_REF}" --format '{{.Id}}') || fail "the loaded image cannot be found"
    fi
    # a registry digest in the archive has to be the pinned one; archives without one cannot be checked here
    LOADED_DIGESTS=$(docker image inspect "${LOADED_REF}" --format '{{range .RepoDigests}}{{println .}}{{end}}')
    if [ -n "${LOADED_DIGESTS}" ] && ! echo "${LOADED_DIGESTS}" | grep -q "${NODERED_DIGEST}"; then
        fail "the image in the archive is not the pinned one (${LOADED_DIGESTS})"
    fi
    USE_REF="${NODERED_REGISTRY}/${NODERED_REPO}:${NODERED_TAG}"
    docker tag "${LOADED_ID}" "${USE_REF}" || fail "tagging the loaded image failed"
    log "image from the archive is tagged ${USE_REF}"
else
    log "pulling ${IMAGE_REF}"
    timeout "${PULL_TIMEOUT:-1800}" docker pull "${IMAGE_REF}" 2>&1 | while IFS= read -r line; do log "docker: ${line}"; done
    docker image inspect "${IMAGE_REF}" > /dev/null 2>&1 || fail "pulling the image failed"
fi

# The modules contain native code: they only work with the Node version they were built for
IMAGE_NODE=$(docker image inspect "${USE_REF}" --format '{{range .Config.Env}}{{println .}}{{end}}' | sed -n 's/^NODE_VERSION=\([0-9]*\)\..*/\1/p')
WANT_NODE=$(manifest node_major)
[ "${IMAGE_NODE}" = "${WANT_NODE}" ] || fail "the image runs Node ${IMAGE_NODE}, the modules are built for Node ${WANT_NODE}"

# Modules
SUM=$(sha256sum "${PAYLOAD}" | cut -d' ' -f1)
[ "${SUM}" = "$(manifest sha256)" ] || fail "checksum of the modules archive does not match the manifest"

NEED_KB=$(( $(manifest unpacked_kb) * 2 + 102400 ))
AVAIL_KB=$(df -Pk /docker | awk 'NR==2 {print $4}')
[ "${AVAIL_KB}" -ge "${NEED_KB}" ] || fail "not enough free space on /docker (${AVAIL_KB} KB, need ${NEED_KB} KB)"

rm -rf "${WORK}/staged"
mkdir -p "${WORK}/staged"
tar -xzf "${PAYLOAD}" -C "${WORK}/staged" || fail "unpacking the modules failed"
# the container runs as the owner of the data directory and must be able to write the modules (palette manager, npm)
chown -R "$(stat -c %u:%g "${DATA}")" "${WORK}/staged" || fail "setting the owner of the modules failed"
[ -d "${WORK}/staged/node_modules" ] && [ -f "${WORK}/staged/package.json" ] || fail "the modules archive has an unexpected layout"
echo "${PKG_VERSION}" > "${WORK}/staged/.version"
echo "${USE_REF}" > "${WORK}/staged/.image-ref"      # the activation uses exactly what was staged
echo "${IMAGE_REF}" > "${WORK}/staged/.image-canonical"   # what the pinned release says, recorded as "current" afterwards

rm -f "${STATE_DIR}/pending-stage"
: > "${STATE_DIR}/pending-activation"
write_result staged "image and modules are on the device, waiting for the activation"
log "stage done"
