#!/bin/bash
# Launch stremio-libtorrent-server with optional NVIDIA NVENC GPU passthrough.
# Uses the androshack/stremio-libtorrent-server Docker image.
# Provides adaptive piece picking, playhead-first streaming, and HW transcoding.
set -e

NAME="stremio-libtorrent"
IMAGE="androshack/stremio-libtorrent-server:latest"
DATA="${DATA:-/home/rurouni/torrserver-data/libtorrent}"
WEB_PORT="${WEB_PORT:-11470}"
BT_PORT="${BT_PORT:-6881}"
CACHE_SIZE="${CACHE_SIZE:-17179869184}"  # 16GB default

mkdir -p "$DATA"

IPADDRESS="${IPADDRESS:-$(ip route get 1.1.1.1 2>/dev/null | grep -oE 'src [0-9.]+' | cut -d' ' -f2)}"

# Detect GPU
GPU_ARGS=""
if docker run --rm --gpus all --entrypoint true "$IMAGE" >/dev/null 2>&1; then
  GPU_ARGS="--gpus all"
  echo "[launch] NVIDIA GPU detected -> NVENC enabled"
fi
if [ -e /dev/dri ]; then
  GPU_ARGS="$GPU_ARGS --device /dev/dri:/dev/dri"
  echo "[launch] /dev/dri present -> VAAPI enabled"
fi

docker rm -f "$NAME" >/dev/null 2>&1 || true

docker run -d --name "$NAME" --restart unless-stopped $GPU_ARGS \
  -e IPADDRESS="${IPADDRESS}" \
  -e STREMIOSRV_BT_LISTEN_PORT="$BT_PORT" \
  -e STREMIOSRV_CACHE_ROOT=/root/.stremio-server \
  -e STREMIOSRV_CACHE_SIZE="$CACHE_SIZE" \
  -v "$DATA":/root/.stremio-server \
  -p "$WEB_PORT":8080 \
  -p "$BT_PORT":"$BT_PORT"/tcp \
  -p "$BT_PORT":"$BT_PORT"/udp \
  "$IMAGE"

echo "[launch] Container started. Health check in 5s..."
sleep 5
if curl -fsS "http://127.0.0.1:$WEB_PORT/health" >/dev/null 2>&1; then
  echo "[launch] Healthy on port $WEB_PORT"
else
  echo "[launch] Health check failed. Logs:"
  docker logs "$NAME" --tail 20
fi
