#!/bin/sh
set -e

BUILD_TREE=$1
DEST=$(realpath "$2")

echo "Compiling JavaBuilder (Vanilla)..."

PROTO_SRC="$BUILD_TREE/proto_src"
CLASSES="$BUILD_TREE/classes"

rm -rf "$PROTO_SRC" "$CLASSES"
mkdir -p "$PROTO_SRC" "$CLASSES"

# Generate proto Java sources
echo "Generating proto Java sources..."
protoc --java_out="$PROTO_SRC" -I"$BUILD_TREE/src/main/protobuf" "$BUILD_TREE/src/main/protobuf/deps.proto"
protoc --java_out="$PROTO_SRC" -I"$BUILD_TREE/src/main/protobuf" "$BUILD_TREE/src/main/protobuf/worker_protocol.proto"
protoc --java_out="$PROTO_SRC" -I"$BUILD_TREE/src/main/protobuf" "$BUILD_TREE/src/main/protobuf/java_compilation.proto"

# Compile Java sources
echo "Compiling Java sources..."
javac -d "$CLASSES" \
    -sourcepath "$BUILD_TREE/src/java_tools/buildjar/java:$PROTO_SRC" \
    -cp /usr/share/java/guava.jar:/usr/share/java/protobuf-java.jar:/usr/share/java/protobuf.jar:/usr/share/java/jsr305.jar:/usr/share/java/error_prone_annotations.jar:/usr/share/java/auto-value-annotations.jar \
    -processorpath /usr/share/java/auto-value.jar:/usr/share/java/auto-common.jar:/usr/share/java/javapoet.jar:/usr/share/java/guava.jar:/usr/share/java/escapevelocity.jar \
    "$BUILD_TREE/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/VanillaJavaBuilder.java" \
    "$BUILD_TREE/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/JavacOptions.java"

# Determine dependencies paths
if [ -f /usr/share/java/protobuf-java.jar ]; then
    PROTO_JAR="/usr/share/java/protobuf-java.jar"
elif [ -f /usr/share/java/protobuf.jar ]; then
    PROTO_JAR="/usr/share/java/protobuf.jar"
else
    echo "ERROR: Protobuf jar not found!"
    exit 1
fi

# Create manifest
echo "Creating manifest..."
MANIFEST_FILE=$(realpath manifest.txt)
echo "Manifest-Version: 1.0" > "$MANIFEST_FILE"
echo "Main-Class: com.google.devtools.build.buildjar.VanillaJavaBuilder" >> "$MANIFEST_FILE"
echo "Class-Path: /usr/share/java/guava.jar $PROTO_JAR" >> "$MANIFEST_FILE"

# Package jar
echo "Packaging jar..."
# We need to be in the classes directory to package the compiled classes
cd "$CLASSES"
jar cfm "$DEST" "$MANIFEST_FILE" .
rm -f "$MANIFEST_FILE"

echo "JavaBuilder compiled successfully."
