#!/bin/bash
#
# Copyright (C) 2026 The pgmoneta community
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# Entrypoint for the Ollama container.
#
# Starts the Ollama server, waits for it to be ready,
# and pulls the default model on first run.

set -e

MODEL="${OLLAMA_MODEL:-llama3.1:8b}"

# Start Ollama server in the background
ollama serve &
SERVER_PID=$!

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

# Pull the default model if not already present
if ! ollama list 2>/dev/null | grep -q "^${MODEL%%:*}"; then
    echo "Pulling model: ${MODEL}"
    ollama pull "${MODEL}"
    echo "Model ${MODEL} is ready."
else
    echo "Model ${MODEL} already available."
fi

# Keep the server in the foreground
wait $SERVER_PID
