#!/bin/bash
# scripts/jetson-entrypoint.sh — Start Ollama + AI Proxy on Jetson Orin
set -e

echo "=== AI Proxy — Jetson Orin Edition ==="
echo "Starting Ollama server..."

# Max performance mode (if not already set)
if command -v nvpmodel &>/dev/null; then
    nvpmodel -m 0 2>/dev/null || true
    jetson_clocks 2>/dev/null || true
fi

# Start Ollama in background
OLLAMA_HOST=0.0.0.0:11434 ollama serve &
OLLAMA_PID=$!

# Wait for Ollama to be ready
echo "Waiting for Ollama..."
for i in $(seq 1 30); do
    if curl -sf http://localhost:11434/api/version >/dev/null 2>&1; then
        echo "Ollama ready."
        break
    fi
    sleep 1
done

# Pull default models if not present
echo "Checking models..."
ollama list 2>/dev/null | grep -q "qwen2.5-coder:1.5b" || {
    echo "Pulling qwen2.5-coder:1.5b..."
    ollama pull qwen2.5-coder:1.5b
}
ollama list 2>/dev/null | grep -q "qwen2.5-coder:3b" || {
    echo "Pulling qwen2.5-coder:3b..."
    ollama pull qwen2.5-coder:3b
}

echo "Starting AI Proxy on :4000..."
export OLLAMA_BASE_URL=http://localhost:11434

# Start proxy (foreground)
exec proxym --host 0.0.0.0 --port 4000
