#!/bin/bash
# Build script for Coral package manager
#
# Builds coral from source tarball using Reef compiler

set -e

# Find source directory — SRCDIR from coral, or auto-detect
if [ -z "$SRCDIR" ] || [ ! -d "$SRCDIR" ]; then
    WORKDIR="${SRCDIR:-$(pwd)}"
    SRCDIR="$(cd "$WORKDIR" && ls -d */ 2>/dev/null | head -1)"
    SRCDIR="${WORKDIR}/${SRCDIR%/}"
fi
cd "$SRCDIR"

# Set up Reef environment (bootstrap installs to /usr)
export PATH="/usr/bin:$PATH"
export LIBRARY_PATH="/usr/lib/reef/runtime/lib:/usr/lib:${LIBRARY_PATH:-}"

# Build with illumos socket libraries explicitly
echo "Building Coral..."
reefc build -l socket -l nsl

# Find the built binary (named after directory)
BINARY=$(ls build/coral* 2>/dev/null | head -1)
if [ -z "$BINARY" ]; then
    echo "Error: No binary found in build/"
    exit 1
fi
echo "Built binary: $BINARY"

# Install
mkdir -p "$PKGDIR$PREFIX/bin"
cp "$BINARY" "$PKGDIR$PREFIX/bin/coral"
chmod +x "$PKGDIR$PREFIX/bin/coral"

# Create initial config directory structure
mkdir -p "$PKGDIR$SYSCONFDIR/coral"
mkdir -p "$PKGDIR/var/lib/coral/installed"
mkdir -p "$PKGDIR/var/lib/coral/packages"
mkdir -p "$PKGDIR/var/lib/coral/sources"
mkdir -p "$PKGDIR/var/lib/coral/trusted-keys"
mkdir -p "$PKGDIR/var/tmp/coral/work"
mkdir -p "$PKGDIR/var/tmp/coral/pkg"
