#!/bin/sh
# Browser transfers through stock USB networking, restricted to InkHub folders.
set -eu
root=${INKHUB_REMARKABLE_ROOT:-/home/root/inkhub-dev}
# The cable's interface, handed down by the session from this board's
# profile. See tools/remarkable-share.sh for the whole reason.
iface=${INKHUB_USB_IFACE:-usb0}
"$root/bin/remarkable-share" --usb "$@"
# Keep cable removal handling alive while Reader or an app owns the screen.
# A single watcher exists only while cable sharing is active. All descriptors
# inherited from the UI's bounded helper are closed before it is detached.
if [ "${1:-}" = start ]; then
    (
        exec 8>/run/inkhub-remarkable-usb-share/watch.lock
        flock -n 8 || exit 0
        while [ -f /run/inkhub-remarkable-usb-share/share.pid ]; do
            pid=$(cat /run/inkhub-remarkable-usb-share/share.pid 2>/dev/null || true)
            case "$pid" in ''|*[!0-9]*) break ;; esac
            [ "$(readlink "/proc/$pid/exe" 2>/dev/null || true)" = "$root/bin/dufs" ] || break
            if [ "$(cat "/sys/class/net/$iface/carrier" 2>/dev/null || true)" != 1 ]; then
                "$root/bin/remarkable-share" --usb stop 8>&- || true
                break
            fi
            sleep 2
        done
    ) </dev/null >/dev/null 2>&1 &
fi
