#!/bin/sh
# Installed beside the common helper in InkHub's private bin directory.
set -eu
root=${INKHUB_REMARKABLE_ROOT:-/home/root/inkhub-dev}
export LIBRA2_SHARE_LAYOUT="$root/share.conf"
export LIBRA2_SHARE_SERVER="$root/bin/dufs"
export LIBRA2_SHARE_ASSETS="$root/share"
export LIBRA2_SHARE_BOOKS="$root/books"
export LIBRA2_SHARE_NOTES="$root/notes"
export LIBRA2_SHARE_LOG_DIR="$root/run"
export LIBRA2_SHARE_RUN_DIR=/run/inkhub-remarkable-share
if [ "${1:-}" = --usb ]; then
    shift
    export LIBRA2_SHARE_TRANSPORT=usb
    # THE GADGET INTERFACE IS THIS BOARD'S, NOT A CONSTANT. The session
    # hands it down in INKHUB_USB_IFACE, from inkhub-platform's profile
    # (examples/remarkable/sharing.rs, run_observed). usb0 is the default
    # for a hand run with no session in front of it, and it is right on
    # the Kobo and the reMarkable 1; on the reMarkable 2 the cable is
    # usb1 and usb0 is there with carrier 0.
    export LIBRA2_SHARE_IFACE=${INKHUB_USB_IFACE:-usb0}
    export LIBRA2_SHARE_PORT=8081
    export LIBRA2_SHARE_RUN_DIR=/run/inkhub-remarkable-usb-share
fi
mkdir -p "$LIBRA2_SHARE_RUN_DIR"
# The server must not inherit the lock. Serialize UI and central sleep calls.
exec 9>"$LIBRA2_SHARE_RUN_DIR/control.lock"
flock -x 9
# A process number can be reused after a crashed development session. Never
# let its old pidfile identify an unrelated stock process as our server.
pidfile="$LIBRA2_SHARE_RUN_DIR/share.pid"
if [ -f "$pidfile" ]; then
    pid=$(cat "$pidfile")
    case "$pid" in
        ''|*[!0-9]*) rm -f "$pidfile" ;;
        *) [ "$(readlink "/proc/$pid/exe" 2>/dev/null || true)" = "$LIBRA2_SHARE_SERVER" ] || rm -f "$pidfile" ;;
    esac
fi
"$root/bin/libra2-share-wifi" "$@" 9>&-
