#!/bin/bash
# Build and install GP sampler as a system-wide shared library
#
# Usage:
#   ./install_library.sh        # Install to /usr/local (requires sudo)
#   ./install_library.sh --user  # Install to ~/.local (no sudo needed)

set -e  # Exit on error

# Detect OS
if [[ "$OSTYPE" == "darwin"* ]]; then
    OS="macos"
    LIB_EXT="dylib"
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
    OS="linux"
    LIB_EXT="so"
else
    echo "Unsupported OS: $OSTYPE"
    exit 1
fi

# Parse arguments
PREFIX="/usr/local"
NEEDS_SUDO=true

if [[ "$1" == "--user" ]]; then
    PREFIX="$HOME/.local"
    NEEDS_SUDO=false
    echo "Installing to user directory: $PREFIX"
else
    echo "Installing to system directory: $PREFIX (requires sudo)"
fi

LIBDIR="$PREFIX/lib"
INCLUDEDIR="$PREFIX/include"
PKGCONFIGDIR="$LIBDIR/pkgconfig"

# Check for GSL
if ! command -v gsl-config &> /dev/null; then
    echo "Error: GSL not found. Install with:"
    if [[ "$OS" == "macos" ]]; then
        echo "  brew install gsl"
    else
        echo "  sudo apt-get install libgsl-dev"
    fi
    exit 1
fi

echo "Building shared library..."

# Build shared library
if [[ "$OS" == "macos" ]]; then
    gcc -O3 -fPIC -dynamiclib gp4c/gp4c.c \
        -o libgp4c.$LIB_EXT \
        -Igp4c $(gsl-config --cflags) $(gsl-config --libs) \
        -install_name "$LIBDIR/libgp4c.$LIB_EXT"
else
    gcc -O3 -fPIC -shared gp4c/gp4c.c \
        -o libgp4c.$LIB_EXT \
        -Igp4c $(gsl-config --cflags) $(gsl-config --libs)
fi

echo "✓ Built libgp4c.$LIB_EXT"

# Extract version from pyproject.toml
VERSION=$(grep '^version = ' pyproject.toml | sed 's/version = "\(.*\)"/\1/')
if [[ -z "$VERSION" ]]; then
    echo "Warning: Could not extract version from pyproject.toml, using 0.0.1"
    VERSION="0.0.1"
fi
echo "Using version: $VERSION"

# Create pkg-config file
cat > gp4c.pc << EOF
prefix=$PREFIX
exec_prefix=\${prefix}
libdir=\${exec_prefix}/lib
includedir=\${prefix}/include

Name: gp4c
Description: High-performance GP sampler for f, integral(f), derivative(f)
Version: $VERSION
Requires: gsl >= 2.0
Libs: -L\${libdir} -lgp4c
Cflags: -I\${includedir}
EOF

echo "✓ Created gp4c.pc (version $VERSION)"

# Create directories
if [[ "$NEEDS_SUDO" == true ]]; then
    sudo mkdir -p "$LIBDIR" "$INCLUDEDIR" "$PKGCONFIGDIR"
else
    mkdir -p "$LIBDIR" "$INCLUDEDIR" "$PKGCONFIGDIR"
fi

# Install files
echo "Installing library and headers..."

if [[ "$NEEDS_SUDO" == true ]]; then
    sudo cp libgp4c.$LIB_EXT "$LIBDIR/"
    sudo cp gp4c/gp4c.h "$INCLUDEDIR/"
    sudo cp gp4c.pc "$PKGCONFIGDIR/"
else
    cp libgp4c.$LIB_EXT "$LIBDIR/"
    cp gp4c/gp4c.h "$INCLUDEDIR/"
    cp gp4c.pc "$PKGCONFIGDIR/"
fi

# Codesign on macOS (required on Apple Silicon to avoid SIGKILL at import time)
if [[ "$OS" == "macos" ]]; then
    echo "Signing library for macOS Apple Silicon..."
    codesign --force --sign - "$LIBDIR/libgp4c.$LIB_EXT"
    echo "✓ Library signed"
fi

echo "✓ Installed to $PREFIX"

# Update library cache (Linux only)
if [[ "$OS" == "linux" ]] && [[ "$NEEDS_SUDO" == true ]]; then
    echo "Updating library cache..."
    sudo ldconfig
    echo "✓ Updated ldconfig cache"
fi

# Add to PATH if user install
if [[ "$NEEDS_SUDO" == false ]]; then
    echo ""
    echo "Note: Add this to your ~/.bashrc or ~/.zshrc:"
    echo "  export PKG_CONFIG_PATH=\"$PKGCONFIGDIR:\$PKG_CONFIG_PATH\""
    if [[ "$OS" != "macos" ]]; then
        echo "  export LD_LIBRARY_PATH=\"$LIBDIR:\$LD_LIBRARY_PATH\""  # Linux only
    fi
    echo "  # Note: DYLD_LIBRARY_PATH not needed on macOS (causes hangs)"
fi

echo ""
echo "Installation complete!"
echo ""
echo "Test with:"
echo "  pkg-config --modversion gp4c"
echo "  pkg-config --cflags --libs gp4c"
echo ""
echo "Use in your code:"
echo "  gcc -o solver solver.c \$(pkg-config --cflags --libs gp4c)"
