#!/bin/bash

# AMD NPU Driver Build Script for TUXEDO OS / Ubuntu 24.04
# Author: NPU Setup Assistant
# Date: 2025-08-05

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
NPU_DIR="$(dirname "$SCRIPT_DIR")"
SRC_DIR="$NPU_DIR/src/xdna-driver"
BUILD_DIR="$SRC_DIR/build"
XRT_BUILD_DIR="$SRC_DIR/xrt/build"
PACKAGES_DIR="$NPU_DIR/packages"

echo "======================================"
echo "AMD NPU Driver Build Script"
echo "======================================"

# Function to print colored output
print_status() {
    echo -e "\033[1;32m[INFO]\033[0m $1"
}

print_error() {
    echo -e "\033[1;31m[ERROR]\033[0m $1"
}

# Check if running as root
if [[ $EUID -eq 0 ]]; then
   print_error "This script should not be run as root"
   exit 1
fi

# Step 1: Update submodules
print_status "Updating git submodules..."
cd "$SRC_DIR"
git submodule update --init --recursive

# Step 2: Install dependencies
print_status "Installing build dependencies (requires sudo)..."
sudo "$SRC_DIR/tools/amdxdna_deps.sh" || {
    print_status "Dependency script failed - attempting manual installation..."
    sudo apt-get update
    sudo apt-get install -y build-essential cmake git \
        libboost-all-dev libdrm-dev ocl-icd-dev \
        opencl-headers rapidjson-dev libprotobuf-dev \
        protobuf-compiler python3-dev python3-pybind11 \
        dkms linux-headers-$(uname -r)
}

# Step 3: Build XRT base
print_status "Building XRT base package..."
cd "$XRT_BUILD_DIR"
./build.sh -npu -opt
print_status "Creating XRT DEB packages..."
cd Release
cpack -G DEB

# Step 4: Build XDNA driver
print_status "Building XDNA driver..."
cd "$BUILD_DIR"
./build.sh -release

# Step 5: Copy packages
print_status "Copying packages to $PACKAGES_DIR..."
mkdir -p "$PACKAGES_DIR"
cp "$BUILD_DIR/Release"/*.deb "$PACKAGES_DIR/" 2>/dev/null || true
cp "$XRT_BUILD_DIR/Release"/*.deb "$PACKAGES_DIR/" 2>/dev/null || true

print_status "Build complete! Packages are in: $PACKAGES_DIR"
echo ""
echo "To install the driver, run:"
echo "  $SCRIPT_DIR/install_npu_driver.sh"