#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright (C) 2026 DiogenOS
#
# Launcher: activates the venv + portable Intel runtime, checks the GPU,
# then starts ComfyUI. Extra args are passed through to ComfyUI's main.py
# (e.g. --listen 0.0.0.0 to reach it from other machines on the LAN).
set -e

if [ ! -e /dev/dri/renderD128 ]; then
  echo "ERROR: no /dev/dri/renderD128 - GPU/xe driver not ready. Aborting." >&2
  exit 1
fi

if [ ! -d "$HOME/img-gen" ] || [ ! -f "$HOME/ai-image/intel-rt/env.sh" ]; then
  echo "Not set up yet for this user. Run:  b70-imagegen-setup" >&2
  exit 1
fi

# shellcheck disable=SC1091
source "$HOME/img-gen/bin/activate"
# shellcheck disable=SC1091
source "$HOME/ai-image/intel-rt/env.sh"

MODEL="$HOME/ai-image/ComfyUI/models/checkpoints/flux1-schnell-fp8.safetensors"
if [ ! -f "$MODEL" ]; then
  echo "Note: model not found. Fetch it with:  b70-imagegen-setup --model-only" >&2
fi

python - <<'PY'
import sys, torch
if not torch.xpu.is_available():
    print("ERROR: torch.xpu not available", file=sys.stderr); sys.exit(1)
print("XPU OK:", torch.xpu.device_count(), "device(s):",
      ", ".join(torch.xpu.get_device_name(i) for i in range(torch.xpu.device_count())))
PY

cd "$HOME/ai-image/ComfyUI"
exec python main.py --port 8188 "$@"
