#!/bin/sh
# Private paths and process ownership for the shared Calibre protocol helper.
set -eu
root=${INKHUB_REMARKABLE_ROOT:-/home/root/inkhub-dev}
export LIBRA2_CALIBRE_LAYOUT="$root/calibre.conf"
export LIBRA2_CALIBRE_DAEMON="$root/bin/libra2-calibred"
export LIBRA2_CALIBRE_ONBOARD="$root"
export LIBRA2_CALIBRE_BOOKS="$root/books"
export LIBRA2_CALIBRE_INDEX="$root/cache/calibre-index.tab"
export LIBRA2_CALIBRE_DATA="$root/data"
export LIBRA2_CALIBRE_DRIVE="$root/preferences/calibre-drive.json"
export LIBRA2_CALIBRE_CONF="$root/preferences/calibre.conf"
export LIBRA2_CALIBRE_NAME_FILE="$root/device-name"
export LIBRA2_CALIBRE_LOG_DIR="$root/run"
export LIBRA2_CALIBRE_RUN_DIR="$root/run/calibre"
mkdir -p "$LIBRA2_CALIBRE_RUN_DIR"
exec 9>"$LIBRA2_CALIBRE_RUN_DIR/control.lock"
flock -x 9
# A stale pidfile must never identify an unrelated stock process.
pidfile="$LIBRA2_CALIBRE_RUN_DIR/calibre.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_CALIBRE_DAEMON" ] || rm -f "$pidfile" ;;
    esac
fi
# The daemon must not inherit the control lock.
"$root/bin/libra2-calibre" "$@" 9>&-
