use std::env;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
fn main() {
println!("cargo:rerun-if-env-changed=LLAMA_SERVER_BUILD");
let should_build = env::var("LLAMA_SERVER_BUILD").is_ok_and(|v| v == "1");
if !should_build {
return;
}
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let project_root = manifest_dir
.parent()
.and_then(|p| p.parent())
.expect("expected project root two levels up from foundation_ai");
let llama_dir = project_root.join("infrastructure/llama-bindings/llama.cpp");
let output_dir = project_root.join("support/bin");
let output_bin = output_dir.join("llama-server");
if !llama_dir.join("CMakeLists.txt").exists() {
println!(
"cargo:warning=llama.cpp source not found at {}",
llama_dir.display()
);
println!("cargo:warning=Run: git submodule update --init infrastructure/llama-bindings/llama.cpp");
return;
}
let build_dir = llama_dir.join("build");
let cmake_cache = build_dir.join("CMakeCache.txt");
let src_bin = build_dir.join("bin/llama-server");
if src_bin.exists() && output_bin.exists() && cmake_cache.exists() {
println!(
"cargo:warning=llama-server already built at {}",
output_bin.display()
);
println!(
"cargo:rustc-env=LLAMA_SERVER_BIN_PATH={}",
output_bin.display()
);
return;
}
fs::create_dir_all(&build_dir).unwrap();
let status = Command::new("cmake")
.current_dir(&build_dir)
.args([
"..",
"-DLLAMA_BUILD_SERVER=ON",
"-DLLAMA_BUILD_TOOLS=ON",
"-DLLAMA_BUILD_TESTS=OFF",
"-DLLAMA_BUILD_EXAMPLES=OFF",
"-DLLAMA_BUILD_APP=OFF",
"-DLLAMA_BUILD_UI=OFF",
"-DLLAMA_BUILD_HTML=OFF",
"-DLLAMA_BUILD_COMMON=ON",
"-DBUILD_SHARED_LIBS=OFF",
"-DCMAKE_BUILD_TYPE=Release",
])
.status()
.expect("failed to run cmake");
assert!(status.success(), "cmake configure failed for llama-server");
let nproc =
std::thread::available_parallelism().map_or_else(|_| "4".into(), |n| n.get().to_string());
let status = Command::new("make")
.current_dir(&build_dir)
.args(["llama-server", &format!("-j{nproc}")])
.status()
.expect("failed to run make");
assert!(status.success(), "make llama-server failed");
assert!(
src_bin.exists(),
"llama-server binary not found at {} after build",
src_bin.display()
);
fs::create_dir_all(&output_dir).unwrap();
fs::copy(&src_bin, &output_bin).unwrap();
println!(
"cargo:warning=llama-server built at {}",
output_bin.display()
);
println!(
"cargo:rustc-env=LLAMA_SERVER_BIN_PATH={}",
output_bin.display()
);
}