#!/bin/bash
# Build osdialog static library for Linux (zenity backend)
set -e

OSDIALOG_DIR="$(dirname "$0")/vendor/osdialog"
OUTPUT_DIR="$(dirname "$0")/build"
mkdir -p "$OUTPUT_DIR"

LIB_OUT="$OUTPUT_DIR/libosdialog.a"

# Only rebuild if sources changed
SOURCES=("$OSDIALOG_DIR/osdialog.c" "$OSDIALOG_DIR/osdialog_zenity.c")
NEED_REBUILD=false
for src in "${SOURCES[@]}"; do
    if [ "$src" -nt "$LIB_OUT" ] 2>/dev/null; then
        NEED_REBUILD=true
        break
    fi
done

if [ "$NEED_REBUILD" = false ] && [ -f "$LIB_OUT" ]; then
    echo "osdialog already built. Skipping."
    exit 0
fi

echo "Building osdialog (zenity backend)..."
for src in "${SOURCES[@]}"; do
    obj="${OUTPUT_DIR}/$(basename "${src%.c}.o")"
    echo "  CC $src"
    gcc -c -O2 -std=c99 -I"$OSDIALOG_DIR" "$src" -o "$obj"
done

ar rcs "$LIB_OUT" "$OUTPUT_DIR"/osdialog.o "$OUTPUT_DIR"/osdialog_zenity.o
echo "  AR $LIB_OUT"
echo "osdialog build complete."
