#!/bin/bash
# Build script for DungeonGenerator
# Usage: ./build.sh [clean|jar|run]

set -e

PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUILD_DIR="$PROJECT_DIR/build/classes"
JAR_FILE="$PROJECT_DIR/DungeonGenerator.jar"
LIB_DIR="$PROJECT_DIR/lib"
SRC_DIR="$PROJECT_DIR/src"
RESOURCES_DIR="$PROJECT_DIR/resources"

# All library JARs
LIBS=$(find "$LIB_DIR" -name "*.jar" | tr '\n' ':')

clean() {
    echo "Cleaning build directory..."
    rm -rf "$PROJECT_DIR/build"
    rm -f "$JAR_FILE"
    rm -f "$PROJECT_DIR/sources.txt"
    echo "Clean complete."
}

compile() {
    echo "Compiling sources..."
    mkdir -p "$BUILD_DIR"

    # Find all Java files
    find "$SRC_DIR" -name "*.java" > "$PROJECT_DIR/sources.txt"

    # Compile
    javac -cp "$LIBS" -d "$BUILD_DIR" @"$PROJECT_DIR/sources.txt"

    # Copy resources
    cp -r "$RESOURCES_DIR"/* "$BUILD_DIR/" 2>/dev/null || true
    cp "$SRC_DIR/version.properties" "$BUILD_DIR/" 2>/dev/null || true

    echo "Compilation complete."
}

create_jar() {
    compile

    echo "Creating JAR..."
    mkdir -p "$BUILD_DIR/META-INF"

    # Create manifest
    LIB_CLASSPATH=$(find "$LIB_DIR" -name "*.jar" -exec basename {} \; | sed 's/^/lib\//' | tr '\n' ' ')
    cat > "$BUILD_DIR/META-INF/MANIFEST.MF" << EOF
Manifest-Version: 1.0
Main-Class: eu.smoser.dungeongenerator.main.DungeonGeneratorUI
Class-Path: $LIB_CLASSPATH

EOF

    # Create JAR
    cd "$BUILD_DIR"
    jar cfm "$JAR_FILE" META-INF/MANIFEST.MF .
    cd "$PROJECT_DIR"

    echo "JAR created: $JAR_FILE"
}

run_app() {
    if [ ! -f "$JAR_FILE" ]; then
        create_jar
    fi
    echo "Running DungeonGenerator..."
    java -jar "$JAR_FILE"
}

# Main
case "${1:-jar}" in
    clean)
        clean
        ;;
    compile)
        compile
        ;;
    jar)
        create_jar
        ;;
    run)
        run_app
        ;;
    all)
        clean
        create_jar
        ;;
    *)
        echo "Usage: $0 [clean|compile|jar|run|all]"
        echo "  clean   - Remove build artifacts"
        echo "  compile - Compile Java sources"
        echo "  jar     - Create executable JAR (default)"
        echo "  run     - Build and run the application"
        echo "  all     - Clean and build JAR"
        exit 1
        ;;
esac

