#!/bin/bash
# ============================================================================
# build_llamacpp_omnios.sh
# Build llama.cpp (llama-server) on OmniOS / illumos -- EXPERIMENTAL
#
# NO OFFICIAL illumos SUPPORT in llama.cpp/ggml. This is a PoC: it compiles
# the CPU-only llama-server with the ooce/illumos toolchain. Expect possible
# ggml POSIX-layer build errors; patches may be needed. The working alternative
# on OmniOS remains a Linux LX zone / remote Ollama (see howto.ai/cs-scripts.info).
#
# Verified on: OmniOS r151058 (192.168.2.189), gcc 14.3, cmake 4.4, 4 cores.
#
# Prereqs (already present on r151058): gcc g++ cmake git curl
#   pkg install ooce/developer/ninja      (or: developer/gmake)
#
# Usage:
#   bash ./build_llamacpp_omnios.sh
# ============================================================================
set -e
set -o pipefail
if [ -z "${BASH_VERSION:-}" ]; then
    echo "ERROR: run with bash:  bash $0"; exit 1
fi

# ---- 0. prerequisites -----------------------------------------------------
for c in git cmake gcc g++; do
    command -v "$c" >/dev/null 2>&1 || { echo "missing: $c"; exit 1; }
done
# illumos make is NOT GNU make -> CMake-generated files fail; need ninja or gmake
if command -v ninja >/dev/null 2>&1; then
    GEN=(-G Ninja)
elif command -v gmake >/dev/null 2>&1; then
    GEN=(-DCMAKE_MAKE_PROGRAM=/usr/bin/gmake)
else
    echo "need ninja or gmake:  pkg install ooce/developer/ninja  (or developer/gmake)"; exit 1
fi

BUILD_DIR="/root/llama.cpp"
LOG="/tmp/llamacpp-build.log"

# ---- 1. source -----------------------------------------------------------
cd /root
if [ ! -d "$BUILD_DIR/.git" ]; then
    git clone --depth 1 https://github.com/ggml-org/llama.cpp.git "$BUILD_DIR"
fi
cd "$BUILD_DIR"
git pull --ff-only 2>/dev/null || true

# ---- 2. configure (CPU only) ---------------------------------------------
cmake -B build "${GEN[@]}" -DCMAKE_BUILD_TYPE=Release \
    -DGGML_CUDA=OFF -DGGML_VULKAN=OFF -DGGML_HIP=OFF -DGGML_METAL=OFF \
    -DGGML_SYCL=OFF -DGGML_NATIVE=ON 2>&1 | tee "$LOG"

# ---- 3. build llama-server ------------------------------------------------
cmake --build build --target llama-server -j"$(nproc 2>/dev/null || echo 4)" 2>&1 | tee -a "$LOG"

# ---- 4. install ------------------------------------------------------------
BIN="$(find build -name llama-server -type f | head -1)"
if [ -n "$BIN" ] && [ -x "$BIN" ]; then
    cp "$BIN" /usr/local/bin/llama-server 2>/dev/null || cp "$BIN" /root/llama-server
    echo "OK: llama-server installed."
    ( /usr/local/bin/llama-server --version 2>&1 || /root/llama-server --version 2>&1 ) | head -2
else
    echo "ERROR: llama-server binary not found under build/"; exit 1
fi
