#!/usr/bin/env bash
set -e

OUT=jar
MAIN_CLASS=de.unitrier.st.uap.w25.tram.Main
JAR_NAME=tram.jar
LIB=lib
TMP=$OUT/tmp

# Clean and prepare
rm -rf "$OUT"
mkdir -p "$TMP"

# 1. Compile sources
if [ -d "$LIB" ]; then
    javac -d "$TMP" -cp "$LIB/*" $(find src -name "*.java")
else
    javac -d "$TMP" $(find src -name "*.java")
fi

# 2. Unpack dependency jars
if [ -d "$LIB" ]; then
    for jar in "$LIB"/*.jar; do
        [ -f "$jar" ] && jar xf "$jar" -C "$TMP"
    done
fi

# 3. Copy resources (including log4j2.xml) into the JAR
if [ -d "resources" ]; then
    cp -r resources/* "$TMP/"
fi

# 4. Create manifest
echo "Main-Class: $MAIN_CLASS" > "$TMP/MANIFEST.MF"

# 5. Package into single jar
jar cfm "$OUT/$JAR_NAME" "$TMP/MANIFEST.MF" -C "$TMP" .

# 6. Clean temporary files
rm -rf "$TMP"

echo "Built: $OUT/$JAR_NAME"
echo "Run with:"
echo "  java -jar $OUT/$JAR_NAME"
