#!/usr/bin/env bash
# VoxCast Server — native install on Debian/Ubuntu (no Docker).
# Creates a venv with the NVIDIA cuDNN/cuBLAS pip wheels (no system CUDA
# toolkit needed, only the NVIDIA driver), a service user, data dir, and a
# systemd unit. Run with sudo.
set -euo pipefail

INSTALL_DIR="/opt/voxcast-server"
DATA_DIR="/var/lib/voxcast"
SERVICE_USER="voxcast"
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"

if [[ $EUID -ne 0 ]]; then
  echo "Please run as root (sudo)." >&2
  exit 1
fi

echo "[1/6] Installing system packages..."
apt-get update
apt-get install -y --no-install-recommends python3.12 python3.12-venv ffmpeg ca-certificates

echo "[2/6] Creating service user and directories..."
id -u "$SERVICE_USER" &>/dev/null || useradd --system --home "$INSTALL_DIR" --shell /usr/sbin/nologin "$SERVICE_USER"
mkdir -p "$INSTALL_DIR" "$DATA_DIR"

echo "[3/6] Copying application..."
cp -r "$REPO_ROOT/src" "$INSTALL_DIR/"
cp -r "$REPO_ROOT/compute_server" "$INSTALL_DIR/"

echo "[4/6] Creating venv and installing dependencies..."
python3.12 -m venv "$INSTALL_DIR/venv"
"$INSTALL_DIR/venv/bin/pip" install --no-cache-dir --upgrade pip
"$INSTALL_DIR/venv/bin/pip" install --no-cache-dir -r "$INSTALL_DIR/compute_server/requirements.txt"
# CUDA runtime as pip wheels (driver-only host). Harmless on CPU-only boxes.
"$INSTALL_DIR/venv/bin/pip" install --no-cache-dir "nvidia-cublas-cu12" "nvidia-cudnn-cu12==9.*" || \
  echo "  (nvidia wheels skipped — CPU-only install)"

echo "[5/6] Writing systemd unit..."
# Point LD_LIBRARY_PATH at the nvidia wheel lib dirs so ctranslate2 finds cuDNN.
NV_LIBS="$("$INSTALL_DIR/venv/bin/python" - <<'PY'
import glob, os, site
paths = []
for base in site.getsitepackages():
    paths += glob.glob(os.path.join(base, "nvidia", "*", "lib"))
print(os.pathsep.join(sorted(set(paths))))
PY
)"
UNIT_SRC="$INSTALL_DIR/compute_server/deploy/voxcast-server.service"
UNIT_DST="/etc/systemd/system/voxcast-server.service"
cp "$UNIT_SRC" "$UNIT_DST"
if [[ -n "$NV_LIBS" ]]; then
  sed -i "/^ExecStart=/i Environment=LD_LIBRARY_PATH=${NV_LIBS}" "$UNIT_DST"
fi
chown -R "$SERVICE_USER:$SERVICE_USER" "$INSTALL_DIR" "$DATA_DIR"

echo "[6/6] Enabling service..."
systemctl daemon-reload
systemctl enable --now voxcast-server

echo
echo "VoxCast Server installed. The API key was generated on first start:"
echo "  journalctl -u voxcast-server | grep -A2 'API key'"
echo "Configure the client with this machine's address on port 8590."
