#!/bin/sh
BASE="/mnt/onboard/.adds/kobo-sideload-sync"
BIN="$BASE/bin/kobo-receiver"
umask 077
. "$BASE/action-timing.sh"
flow_id="$(kss_active_flow_id_read 2>/dev/null)" || flow_id=""
if ! kss_flow_id_is_valid "$flow_id" || ! kss_flow_is_current "$flow_id" || [ ! -s "$BASE/run/session.json" ]; then
    /bin/sh "$BASE/status.sh" --compact 2>&1 | sed 's/完成传书并导入/结束无线传输/g'
    echo "请先开启无线传输。"
    exit 0
fi
image="$BASE/run/add-code-$$.png"
# Session ticket stays in the private file/header, never shell arguments/logs.
output="$($BIN --connection-display --display-on-device --session-file="$BASE/run/session.json" --pairing-image-file="$image" 2>/dev/null)"
result=$?
if [ "$result" -ne 0 ]; then
    /bin/sh "$BASE/status.sh" --compact 2>&1 | sed 's/完成传书并导入/结束无线传输/g'
    echo ""
    printf '%s\n' "$output"
    rm -f "$image"
    exit 0
fi
# The CLI formats status, a reserved QR space and instructions as one layout.
printf '%s\n' "$output"
# Receiver owns the guard, drawing process, cancellation and image cleanup.
exit 0
