#!/bin/sh

BASE="/mnt/onboard/.adds/kobo-sideload-sync"
FBINK="$BASE/third-party/fbink/bin/fbink"
FBINK_LIB_DIR="$BASE/third-party/fbink/lib"
STATUS_FILE="$BASE/run/status.txt"
WAIT_TENTHS="${KSS_PAIRING_WAIT_TENTHS:-0}"

if [ -r "$BASE/action-timing.sh" ]; then
    . "$BASE/action-timing.sh"
else
    kss_timing_event() { :; }
fi

flow_id="${KSS_FLOW_ID:-}"
if ! kss_flow_id_is_valid "$flow_id" || ! kss_flow_is_current "$flow_id"; then
    kss_timing_event qr_flow_mismatch
    echo "本次二维码流程已经取消或被替换。"
    exit 0
fi
KSS_FLOW_ID="$flow_id"
export KSS_FLOW_ID

kss_timing_event qr_worker_begin

case "$WAIT_TENTHS" in
    ''|*[!0-9]*) WAIT_TENTHS=0 ;;
esac

# Give NickelMenu time to paint its real modal touch guard before FBInk draws
# the QR. Zero delay races Nickel's redraw; one second is the shortest
# conservative whole-second delay for the Kobo shell environment.
kss_timing_event qr_guard_wait_begin
sleep 1
kss_timing_event qr_guard_wait_end

if ! kss_flow_is_current "$flow_id"; then
    kss_timing_event qr_flow_mismatch
    exit 0
fi

if [ ! -x "$FBINK" ] || [ ! -r "$FBINK_LIB_DIR/libfbink.so.1" ]; then
    kss_timing_event qr_fail
    echo "FBInk 私有组件不可用。"
    exit 1
fi
attempt=0
kss_timing_event qr_status_wait_begin
while [ ! -s "$STATUS_FILE" ] && [ "$attempt" -lt "$WAIT_TENTHS" ]; do
    if ! kss_flow_is_current "$flow_id"; then
        kss_timing_event qr_flow_mismatch
        exit 0
    fi
    attempt=$((attempt + 1))
    sleep 0.1
done
if [ ! -s "$STATUS_FILE" ]; then
    kss_timing_event qr_status_wait_timeout
    echo "Receiver 尚未生成会话状态。"
    exit 1
fi
kss_timing_event qr_status_wait_end

if ! kss_flow_is_current "$flow_id"; then
    kss_timing_event qr_flow_mismatch
    exit 0
fi

pairing_image="$(sed -n 's/^PAIRING_IMAGE_FILE=//p' "$STATUS_FILE")"
if [ -z "$pairing_image" ] || [ ! -s "$pairing_image" ]; then
    kss_timing_event qr_fail
    echo "Receiver 尚未生成二维码图片。"
    exit 1
fi

# FBInk is deliberately private to this project. The upstream CLI expects its
# matching shared library; LD_LIBRARY_PATH avoids global /usr/bin or /usr/local
# installation and prevents interference with other Kobo add-ons.
LD_LIBRARY_PATH="$FBINK_LIB_DIR${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
export LD_LIBRARY_PATH

# Keep NickelMenu's real modal dialog visible around the QR. The dialog owns
# touch input, so a dismissal cannot activate a book underneath. In particular,
# do not use FBInk --clear here: that would visually erase the modal guard.
if ! kss_flow_is_current "$flow_id"; then
    kss_timing_event qr_flow_mismatch
    exit 0
fi
kss_timing_event qr_fbink_begin
"$FBINK" -f -w -i "$pairing_image" -g y=160,halign=CENTER,valign=TOP
result=$?
if [ "$result" -eq 0 ]; then
    kss_timing_event qr_fbink_ok
else
    kss_timing_event qr_fbink_fail
fi
exit "$result"
