#!/bin/bash
#
# Veil Browser Build Script
# Linux build only
#

set -e

PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
BUILD_DIR="$PROJECT_DIR/build"
SRC="$PROJECT_DIR/src/veil.c"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

print_status() { echo -e "${GREEN}[*]${NC} $1"; }
print_warn() { echo -e "${YELLOW}[!]${NC} $1"; }
print_error() { echo -e "${RED}[x]${NC} $1"; }

show_help() {
    echo "Veil Browser Build Script"
    echo ""
    echo "Usage: $0 [target]"
    echo ""
    echo "Targets:"
    echo "  build     Build for Linux (default)"
    echo "  clean     Remove build artifacts"
    echo "  help      Show this help"
    echo ""
}

build_linux() {
    print_status "Building Veil for Linux..."

    # Check dependencies
    if ! pkg-config --exists gtk+-3.0 webkit2gtk-4.1 2>/dev/null; then
        print_error "Missing dependencies. Install: gtk3 webkit2gtk"
        exit 1
    fi

    CFLAGS=$(pkg-config --cflags gtk+-3.0 webkit2gtk-4.1)
    LIBS=$(pkg-config --libs gtk+-3.0 webkit2gtk-4.1)

    mkdir -p "$BUILD_DIR/linux"

    gcc $CFLAGS \
        -O3 -march=native -mtune=native -flto -ffast-math \
        -fomit-frame-pointer -pipe \
        -Wall -Wextra -Wno-unused-parameter \
        -o "$BUILD_DIR/linux/veil" "$SRC" \
        $LIBS -flto -Wl,-O1 -Wl,--as-needed

    # Copy to project root
    cp "$BUILD_DIR/linux/veil" "$PROJECT_DIR/veil"

    print_status "Build complete: $BUILD_DIR/linux/veil"
    print_status "Also copied to: $PROJECT_DIR/veil"
}

clean() {
    print_status "Cleaning build artifacts..."
    rm -rf "$BUILD_DIR"
    rm -f "$PROJECT_DIR/veil"
    print_status "Clean complete."
}

# Main
cd "$PROJECT_DIR"

case "${1:-build}" in
    build|linux)
        build_linux
        ;;
    clean)
        clean
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        print_error "Unknown target: $1"
        show_help
        exit 1
        ;;
esac
