#!/bin/bash
# GPU 节点（Linux / Vast 容器）依赖安装。顺序与标记与 deploy_node.onstart 完全一致（那套是实测出来的）：
#   1) 系统库  2) aiortc 组  3) ML 组（insightface 会带入 CPU 版 onnxruntime）  4) 卸掉 ORT 重装 GPU 版
#   5) opencv 换 headless  6) CUDA 门禁
# 镜像：pytorch/pytorch:2.13.0-cuda13.0-cudnn9-runtime（已含 torch）。
set -o pipefail
cd "$(dirname "$0")"
nvidia-smi -L || { echo "###FATAL_NO_GPU###"; exit 1; }
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq >/dev/null 2>&1
apt-get install -y -qq libgl1 libglib2.0-0 libxcb1 libsm6 libxext6 curl >/dev/null 2>&1
PIPQ="pip install --break-system-packages --root-user-action=ignore -q"
# 镜像里的 cryptography 是 apt 装的没有 RECORD，只对它 --ignore-installed
$PIPQ --ignore-installed cryptography >/tmp/pip0.log 2>&1 || { echo "###E_PIP_CRYPTO###"; tail -20 /tmp/pip0.log; }
$PIPQ aiortc aiohttp av >/tmp/pip1.log 2>&1 || { echo "###E_PIP_RTC###"; tail -40 /tmp/pip1.log; exit 1; }
echo "###PIP_RTC_OK###"
$PIPQ insightface opencv-python-headless onnx diffusers transformers >/tmp/pip2.log 2>&1 || { echo "###E_PIP_ML###"; tail -40 /tmp/pip2.log; exit 1; }
pip uninstall -y -q onnxruntime onnxruntime-gpu >/dev/null 2>&1
$PIPQ onnxruntime-gpu >/tmp/pip3.log 2>&1 || { echo "###E_PIP_ORT###"; tail -40 /tmp/pip3.log; exit 1; }
python -c "import onnxruntime as o;print('###ORT###',o.__version__,o.get_available_providers())"
pip uninstall -y -q opencv-python >/dev/null 2>&1
$PIPQ opencv-python-headless >/dev/null 2>&1
python -c "import aiortc,aiohttp,av;print('###VER### aiortc',aiortc.__version__)"
python -c "import torch; torch.zeros(1).cuda()" 2>/tmp/cuda.log && echo "###CUDA_OK###" || { echo "###FATAL_CUDA###"; tail -3 /tmp/cuda.log; exit 1; }
mkdir -p assets
[ -s assets/talking.mp4 ] || curl -sL -A "Mozilla/5.0" -e "https://www.pexels.com/" -o assets/talking.mp4 \
  "https://videos.pexels.com/video-files/9710163/9710163-hd_1920_1080_25fps.mp4" || true
ls -l assets/ | head -20
echo "###INSTALL_OK###"
