#!/bin/bash
# /usr/bin/tenni-client from the tenni-client .deb.
# The station lives in /var/lib/tenni-client (settings.ini, out/, cache/,
# whisper models) and the service runs as the "tenni" user. Run by anyone
# else, this re-runs itself with sudo and gives the files back to "tenni".
#
#   tenni-client --setup        setup wizard (radios, systems, API key, service)
#   tenni-client status         what the running station is doing
#   tenni-client service ...    start | stop | restart | logs | enable | disable
#   tenni-client                run in this terminal
set -uo pipefail
DATA=/var/lib/tenni-client
APP=/usr/lib/tenni-client

if [ "$(id -u)" != 0 ] && [ "$(id -un)" != tenni ]; then
  exec sudo "$0" "$@"
fi

export OP25_APPS="$APP/op25/op25/gr-op25_repeater/apps"
export WHISPER_BIN="$APP/bin/whisper-server"
export WHISPER_DIR="$DATA/whisper"
export PATH="$APP/bin:$PATH"
export PYTHONUNBUFFERED=1 TENNI_PACKAGED=1
# local overrides, e.g. WHISPER_MODEL=small.en-q5_1 or OP25_HTTP_HOST=0.0.0.0
[ -r /etc/default/tenni-client ] && . /etc/default/tenni-client

mkdir -p "$DATA/out" "$DATA/cache" "$DATA/whisper/models"
if [ ! -f "$DATA/settings.ini" ]; then
  cp "$APP/settings.ini.example" "$DATA/settings.ini"
  echo "[tenni] created $DATA/settings.ini from the example."
  if [ "${1:-}" = "--daemon" ]; then
    echo "[tenni] Configure the station first:  sudo tenni-client --setup"
    exit 1
  fi
fi

case "${1:-}" in
  status|service)
    sub="$1"; shift
    set -- "$sub" --settings "$DATA/settings.ini" --out "$DATA/out" "$@" ;;
  *)
    set -- --settings "$DATA/settings.ini" --out "$DATA/out" --cache "$DATA/cache" "$@" ;;
esac

if [ "$(id -u)" != 0 ]; then
  exec python3 "$APP/tenni-client.py" "$@"
fi
# root (the wizard, or sudo tenni-client): the service user must still own
# everything it created
python3 "$APP/tenni-client.py" "$@"
rc=$?
chown -R tenni:tenni "$DATA" 2>/dev/null
exit $rc
