#!/bin/bash -eu

tag="snap.$SNAP_INSTANCE_NAME.hook.install"

# Redirect stdout to stdout+syslog
exec 1> >(tee >(logger --tag="$tag"))
# Redirect stderr to stderr+syslog
exec 2> >(logger --stderr --priority error --tag="$tag")

#
# Set generic config
#

# The UbuSTT socket path, under the key modelctl's `status` reads for a
# ws+unix runtime server (runtimes/*/runtime.yaml) to report the entrypoint.
modelctl set --package ws.unix-socket="$SNAP_COMMON/run/ubustt.sock"
modelctl set --package verbose="false"
# Idle-unload: release the model after this many idle seconds (0 = never).
# 5 min keeps frequent dictation warm but frees RAM when you walk away.
modelctl set --package sleep-idle-seconds="300"

#
# Auto select an engine
#
# Audio8 ships two engines (cpu, nvidia-gpu); auto-select the right one from
# the hardware. The --auto fallback covers sideloaded installs where
# hardware-observe is not auto-connected but lscpu is still reachable (dev
# mode / classic assumptions), so the server never starts without an engine.
#

if snapctl is-connected hardware-observe; then
    modelctl use-engine --auto --assume-yes --verbose
elif lscpu -V &> /dev/null; then
    echo "Able to access hardware info without hardware-observe interface connection: assuming dev mode installation."
    modelctl use-engine --auto --assume-yes --verbose
else
    echo "hardware-observe interface not auto connected. Skip auto engine selection."
fi
