#!/bin/bash
# Activates what `stage` prepared: backs up the data, swaps the module tree (keeping the customer's own modules),
# writes the compose override with the pinned image, starts the container and checks its health. Rolls back to the
# previous modules if the container does not become healthy. All local, no network needed (except a retry of stage).
#
# Started by the package postinst (right after the update) and at every boot while a staged update is pending.
# Waits until apt has finished, and until a pending firmware update has been installed and the device rebooted.
. /usr/lib/eurogard/nodered/common.sh

exec 9> /run/eurogard-nodered.lock
flock -n 9 || { log "activation is already running"; exit 0; }

if [ ! -e "${STATE_DIR}/pending-stage" ] && [ ! -e "${STATE_DIR}/pending-activation" ]; then
    exit 0
fi

wait_dpkg_lock || { log "the dpkg lock was never released"; exit 1; }

# The firmware update comes first, the activation follows after its reboot
if [ -e /app/eurogard/rosp-update/pending ] || [ "$(renv get sys_need_reboot 2>/dev/null)" = "true" ]; then
    log "a firmware update is pending, the activation follows after the reboot"
    write_result waiting_reboot "activation follows after the firmware update and the reboot"
    exit 0
fi

attempt=$(( $(cat "${STATE_DIR}/attempts" 2>/dev/null || echo 0) + 1 ))
if [ "${attempt}" -gt "${MAX_ATTEMPTS}" ]; then
    log "giving up after ${MAX_ATTEMPTS} attempts"
    rm -f "${STATE_DIR}/pending-stage" "${STATE_DIR}/pending-activation"
    write_result gave_up "gave up after ${MAX_ATTEMPTS} attempts"
    exit 1
fi
echo "${attempt}" > "${STATE_DIR}/attempts"

PREV="${WORK}/prev"
WAS_RUNNING=0

fail() {
    log "activation failed: $1"
    write_result failed "activate: $1"
    # a container that was running before must not stay stopped because an update failed
    [ "${WAS_RUNNING}" = "1" ] && /usr/lib/eurogard/nodered/ctl start > /dev/null 2>&1
    sync_container_unit
    exit 1
}

stop_container() {
    systemctl stop eurogard-nodered.service > /dev/null 2>&1
    docker stop -t 30 "${CONTAINER}" > /dev/null 2>&1
    return 0
}

rollback() {
    stop_container
    rm -rf "${DATA}/node_modules"
    [ -d "${PREV}/node_modules" ] && mv "${PREV}/node_modules" "${DATA}/node_modules"
    for f in package.json package-lock.json; do
        [ -f "${PREV}/${f}" ] && cp -a "${PREV}/${f}" "${DATA}/${f}"
    done
    if [ -f "${PREV}/docker-compose.override.yaml" ]; then
        cp -a "${PREV}/docker-compose.override.yaml" "${OVERRIDE}"
    else
        rm -f "${OVERRIDE}"
    fi
    if [ "${WAS_RUNNING}" = "1" ]; then
        /usr/lib/eurogard/nodered/ctl start > /dev/null 2>&1
    fi
}

# Do not `systemctl start` the container unit from here: it is ordered after this unit and would wait for it
# (deadlock). The container is started with ctl, the unit is brought in sync once this unit has finished.
sync_container_unit() {
    systemctl start --no-block eurogard-nodered.service > /dev/null 2>&1
}

# Retry what the update could not finish (e.g. no internet during the update)
if [ -e "${STATE_DIR}/pending-stage" ]; then
    log "staging was not completed, trying again"
    timeout 900 /usr/lib/eurogard/nodered/stage || fail "staging failed again"
fi
[ -d "${WORK}/staged/node_modules" ] || fail "nothing is staged"

# What was staged is what gets activated, whatever the configuration says by now
[ -f "${WORK}/staged/.image-ref" ] && IMAGE_REF=$(cat "${WORK}/staged/.image-ref")
CURRENT_REF="${IMAGE_REF}"
[ -f "${WORK}/staged/.image-canonical" ] && CURRENT_REF=$(cat "${WORK}/staged/.image-canonical")
[ -f "${WORK}/staged/.version" ] && PKG_VERSION=$(cat "${WORK}/staged/.version")
export IMAGE_REF PKG_VERSION

write_result activating "swapping the modules and starting the container"
log "activation: version ${PKG_VERSION}, image ${IMAGE_REF}"

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"

# 1. backup of the data (flows, credentials, settings), not of the modules
mkdir -p "${WORK}/backup"
BACKUP="${WORK}/backup/data-$(date +%Y%m%d-%H%M%S).tgz"
tar -czf "${BACKUP}" -C "${DATA}" --exclude=./node_modules --exclude=./.npm . 2> /dev/null || log "warning: the backup is incomplete"
ls -1t "${WORK}"/backup/data-*.tgz 2> /dev/null | tail -n +3 | xargs -r rm -f
log "backup: ${BACKUP}"

# 2. stop the container
[ "$(docker inspect -f '{{.State.Running}}' "${CONTAINER}" 2> /dev/null)" = "true" ] && WAS_RUNNING=1
stop_container

# 3. customer-installed modules are carried over into the new tree
REPORT=$(python3 /usr/lib/eurogard/nodered/merge-modules "${DATA}" "${WORK}/staged" "${MANIFEST}" "${MANAGED_FILE}") \
    || fail "merging the customer's modules failed"
echo "${REPORT}" > "${STATE_DIR}/merge-report.json"
log "modules: ${REPORT}"

# 4. swap, the previous tree stays in ${PREV} for a rollback
rm -rf "${PREV}"
mkdir -p "${PREV}"
[ -d "${DATA}/node_modules" ] && mv "${DATA}/node_modules" "${PREV}/node_modules"
for f in package.json package-lock.json; do
    [ -f "${DATA}/${f}" ] && cp -a "${DATA}/${f}" "${PREV}/${f}"
done
[ -f "${OVERRIDE}" ] && cp -a "${OVERRIDE}" "${PREV}/docker-compose.override.yaml"

mv "${WORK}/staged/node_modules" "${DATA}/node_modules" || { rollback; fail "moving the new modules into place failed"; }
cp -a "${WORK}/staged/package.json" "${DATA}/package.json"
[ -f "${WORK}/staged/package-lock.json" ] && cp -a "${WORK}/staged/package-lock.json" "${DATA}/package-lock.json"

# 5. compose override: the pinned image, crash recovery by Docker, the start at boot is done by eurogard-nodered.service
cat > "${OVERRIDE}.tmp" <<EOF
# Written by eurogard-nodered, changes are overwritten by the next update
services:
  node-red:
    image: ${IMAGE_REF}
    restart: on-failure:10
    healthcheck:
      test: ["CMD-SHELL", "node /healthcheck.js"]
      interval: 5s
      timeout: 5s
      retries: 6
      start_period: 20s
EOF
mv "${OVERRIDE}.tmp" "${OVERRIDE}"

# 6. start and check
if fairuse_ok; then
    healthy=0
    status=""
    if /usr/lib/eurogard/nodered/ctl start; then
        log "waiting for the container to become healthy"
        for i in $(seq 1 "${HEALTH_ROUNDS:-60}"); do
            status=$(docker inspect -f '{{.State.Health.Status}}' "${CONTAINER}" 2> /dev/null)
            if [ "${status}" = "healthy" ]; then
                healthy=1
                break
            fi
            sleep 2
        done
    else
        status="the start failed"
    fi
    # A container that does not start or does not become healthy gets the previous modules back
    if [ "${healthy}" -ne 1 ]; then
        log "the container is not healthy (${status}), rolling back. Last log lines:"
        docker logs --tail 20 "${CONTAINER}" 2>&1 | while IFS= read -r line; do log "nodered: ${line}"; done
        rollback
        rm -rf "${WORK}/staged"
        rm -f "${STATE_DIR}/pending-activation"
        write_result rolled_back "the container did not start or become healthy (${status}), the previous modules are back"
        sync_container_unit
        exit 1
    fi
else
    log "the fair use terms are not accepted, the container stays stopped"
fi

# 7. done
python3 - "${MANAGED_FILE}" "${PKG_VERSION}" "${CURRENT_REF}" "${MANIFEST}" <<'EOF'
import json, os, sys
path, version, image, manifest = sys.argv[1:5]
managed = json.load(open(manifest)).get("managed", [])
with open(path, "w") as f:
    json.dump({"version": version, "image": image, "managed": managed}, f)
st = os.stat(os.path.dirname(path))
os.chown(path, st.st_uid, st.st_gid)
EOF
rm -rf "${WORK}/staged"
rm -f "${STATE_DIR}/pending-activation" "${STATE_DIR}/pending-stage" "${STATE_DIR}/attempts"
write_result success "activated"
log "activation done"
sync_container_unit
