#!/bin/sh
# SPDX-License-Identifier: GPL-2.0-or-later
set -u
: "${LIBRA2_APP_DIR:?Missing supervised app directory}"
: "${LIBRA2_DATA_DIR:?Missing private settings directory}"
: "${INKHUB_REMARKABLE_ROOT:?Missing InkHub installation root}"
cd "$LIBRA2_APP_DIR/koreader" || exit 1
test -f reader.lua && test -x luajit || exit 1
export KO_HOME="$LIBRA2_DATA_DIR" INKHUB_KOREADER=1
export KO_DONT_GRAB_INPUT=1 KO_DONT_SET_DEPTH=1 KO_DONT_MANAGE_NETWORK=1
export STARDICT_DATA_DIR=data/dict LC_ALL=en_US.UTF-8
# Forward all lifecycle signals, including those interrupting wait. The SDK
# binds Lua's lifetime to this wrapper with PDEATHSIG, covering forced stops.
child= stopped=0 restarts=0
trap 'stopped=1; test -z "$child" || kill -TERM "$child" 2>/dev/null || :' TERM
trap 'test -z "$child" || kill -USR1 "$child" 2>/dev/null || :' USR1
trap 'test -z "$child" || kill -USR2 "$child" 2>/dev/null || :' USR2
while :; do
    test -z "${LIBRA2_APP_READY_FILE:-}" || rm -f "$LIBRA2_APP_READY_FILE"
    ./luajit ./reader.lua "${LIBRA2_OPEN:-$INKHUB_REMARKABLE_ROOT/books}" &
    child=$!
    while :; do
        wait "$child"; status=$?
        kill -0 "$child" 2>/dev/null || break
    done
    child=
    test "$stopped" = 0 || exit "$status"
    test "$status" = 85 || exit "$status"
    restarts=$((restarts+1))
    test "$restarts" -lt 4 || exit 85
done
