#!/bin/bash
# Launch stremio-libtorrent-server with NVIDIA NVENC on RTX 2080 Ti
set -e

NAME="stremio-libtorrent"
IMAGE="androshack/stremio-libtorrent-server:latest"
DATA="/home/rurouni/torrserver-data/libtorrent"
WEB_PORT="11470"  # HTTP API port for our proxy
BT_PORT="6881"
CACHE_SIZE="17179869184"  # 16GB cache

# Create data dir
mkdir -p "$DATA"

# Get LAN IP for auto HTTPS cert
IPADDRESS=$(ip route get 1.1.1.1 2>/dev/null | grep -oE 'src [0-9.]+' | cut -d' ' -f2)

echo "[launch] Starting stremio-libtorrent-server..."
echo "[launch] IP: $IPADDRESS"
echo "[launch] GPU: RTX 2080 Ti (NVENC)"
echo "[launch] Cache: 16GB"
echo "[launch] API port: $WEB_PORT"
echo "[launch] BT port: $BT_PORT"

# Remove old container if exists
docker rm -f "$NAME" >/dev/null 2>&1 || true

docker run -d --name "$NAME" --restart unless-stopped \
  --gpus all \
  -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. Checking health..."
sleep 5

# Health check
if curl -fsS "http://127.0.0.1:$WEB_PORT/health" >/dev/null 2>&1; then
  echo "[launch] ✅ libtorrent-server healthy on port $WEB_PORT"
  echo "[launch]    API: http://127.0.0.1:$WEB_PORT"
  echo "[launch]    NVENC: enabled"
else
  echo "[launch] ⚠️  Health check failed, checking logs..."
  docker logs "$NAME" --tail 20
fi
