#!/bin/sh /etc/rc.common
# shellcheck disable=SC2034

# Runs whether or not Forkop does: a stopped service is when the page most needs an answer.
START=98
USE_PROCD=1

FORKOP_LIB="/usr/lib/forkop"
FORKOP_STATE_SERVICE_UC="$FORKOP_LIB/service/state_service.uc"
FORKOP_LUCI_VIEW="/www/luci-static/resources/view/forkop/main.js"

# FORKOP_LIB is not exported, so state_service.uc resolves the bytecode cache itself.
resolved_library() {
    ucode -L "$FORKOP_LIB" -e '
        let bytecode = null;
        try {
            bytecode = loadfile("'"$FORKOP_LIB"'/core/bytecode.uc")();
        }
        catch (e) {
        }
        print(bytecode == null ? "'"$FORKOP_LIB"'" : bytecode.refresh(), "\n");
    ' 2>/dev/null || printf '%s\n' "$FORKOP_LIB"
}

# No instance without the LuCI app; its uci-defaults run `forkop luci_postinst`, which
# starts the service once the app is installed.
luci_app_installed() {
    [ -r "$FORKOP_LUCI_VIEW" ]
}

start_service() {
    [ -r "$FORKOP_STATE_SERVICE_UC" ] || return 1
    luci_app_installed || return 0

    local library
    library="$(resolved_library)"
    [ -n "$library" ] || library="$FORKOP_LIB"

    procd_open_instance
    procd_set_param command ucode -L "$library" "$library/service/state_service.uc" run
    procd_set_param env FORKOP_LIB="$library"
    procd_set_param respawn 3600 5 0
    procd_set_param stderr 1
    procd_close_instance
}
