#!/bin/sh

BASE="/mnt/onboard/.adds/kobo-sideload-sync"
LOG_FILE="$BASE/run/pairing-display.log"

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

flow_id="$(kss_active_flow_id_read 2>/dev/null)" || flow_id=""
if ! kss_flow_id_is_valid "$flow_id"; then
    kss_timing_event open_start_fail
    echo "本次开启流程标识不存在或无法读取；Receiver 没有启动。"
    echo "请点击“完成传书并导入”恢复本次 Wi-Fi 保活后再重试。"
    kss_timing_event open_modal_command_returning
    exit 0
fi
KSS_FLOW_ID="$flow_id"
export KSS_FLOW_ID

kss_timing_event open_wrapper_begin

# Spawn the Receiver and return pending without foreground polling. NickelMenu
# can then return to its event loop and paint the native modal touch guard while
# the bounded QR worker follows this exact flow in the background.
start_output="$(KSS_FLOW_ID="$flow_id" KSS_START_WAIT_TENTHS=0 KSS_KEEP_PENDING=1 /bin/sh "$BASE/start.sh" 2>&1)"
start_result=$?
printf '%s\n' "$start_output"
if [ "$start_result" -eq 2 ]; then
    kss_timing_event open_start_pending
    KSS_FLOW_ID="$flow_id" KSS_PAIRING_WAIT_TENTHS=310 /bin/sh "$BASE/show-pairing.sh" </dev/null >>"$LOG_FILE" 2>&1 &
    kss_timing_event open_qr_worker_spawned
    echo "正在开启无线传书，请耐心等待；二维码就绪后会自动显示。"
    echo "请勿重复点击，也不要提前关闭本提示。"
    echo "本次保活已经建立；无论连接结果如何，结束时都请点击“完成传书并导入”。"
    kss_timing_event open_modal_command_returning
    exit 0
fi
if [ "$start_result" -ne 0 ]; then
    kss_timing_event open_start_fail
    # NickelMenu replaces non-zero cmd_output results with its own technical
    # process error. The user-facing wrapper has already printed the useful
    # failure message, so return success only to keep that message visible.
    echo "本次保活可能已经建立；请点击“完成传书并导入”恢复后再重试。"
    kss_timing_event open_modal_command_returning
    exit 0
fi

kss_timing_event open_start_ready

if [ ! -x "$BASE/third-party/fbink/bin/fbink" ] || [ ! -r "$BASE/third-party/fbink/lib/libfbink.so.1" ]; then
    kss_timing_event open_no_fbink
    echo "二维码组件不可用，请按上方局域网地址打开。"
    kss_timing_event open_modal_command_returning
    exit 0
fi

KSS_FLOW_ID="$flow_id" /bin/sh "$BASE/show-pairing.sh" </dev/null >>"$LOG_FILE" 2>&1 &
kss_timing_event open_qr_worker_spawned
echo "请不要提前关闭本提示；约 1 秒后二维码会显示在弹窗上。"
echo "扫码后轻触屏幕任意位置返回；OK 按钮也可关闭。"
kss_timing_event open_modal_command_returning
