#!/bin/bash
# ffg-build.sh — Firefrost Gaming mod build router
# Routes NeoForge 1.21.1 builds to NC1 (RAM headroom for Vineflower -Xmx4G)
# All other versions build locally on Dev Panel
# Usage: ffg-build.sh <mc_version> [gradle_args...]

set -euo pipefail

VERSION="${1:-}"
WORKSPACE="/opt/mod-builds/firefrost-services/services/discord-rules"
NC1_USER="ffg-builder"
NC1_HOST="216.239.104.130"
NC1_KEY="/opt/mod-builds/ffg_build_rsa"
NC1_WORKSPACE="/home/ffg-builder/workspaces/build-$$"

if [[ -z "$VERSION" ]]; then
    echo "[ERROR] Usage: ffg-build.sh <mc_version>"
    echo "        Example: ffg-build.sh 1.21.1"
    exit 1
fi

# Route decision
if [[ "$VERSION" == "1.21.1" ]]; then
    echo "[ROUTING] NeoForge $VERSION — routing build to NC1 (Vineflower RAM requirement)"

    # Trap: clean up NC1 workspace on exit (covers drops, errors, ctrl+c)
    trap 'echo "[CLEANUP] Removing NC1 workspace..."; ssh -i "$NC1_KEY" -o StrictHostKeyChecking=no -o IdentitiesOnly=yes "$NC1_USER@$NC1_HOST" "rm -rf $NC1_WORKSPACE" 2>/dev/null || true' EXIT

    NC1_SSH="ssh -i $NC1_KEY -o StrictHostKeyChecking=no -o IdentitiesOnly=yes"

    # Create workspace on NC1
    ssh -i "$NC1_KEY" -o StrictHostKeyChecking=no -o IdentitiesOnly=yes "$NC1_USER@$NC1_HOST" \
        "mkdir -p $NC1_WORKSPACE"

    # Sync source to NC1 (exclude local build artifacts and gradle cache)
    rsync -az -e "$NC1_SSH" --exclude 'build/' --exclude '.gradle/' \
        "$WORKSPACE/$VERSION/" \
        "$NC1_USER@$NC1_HOST:$NC1_WORKSPACE/"

    echo "[NC1] Running Gradle build..."
    ssh -i "$NC1_KEY" -o StrictHostKeyChecking=no -o IdentitiesOnly=yes "$NC1_USER@$NC1_HOST" \
        "cd $NC1_WORKSPACE && ./gradlew build --no-daemon"

    # Retrieve only the compiled jar
    mkdir -p "$WORKSPACE/$VERSION/build/libs"
    rsync -az -e "$NC1_SSH" \
        "$NC1_USER@$NC1_HOST:$NC1_WORKSPACE/build/libs/" \
        "$WORKSPACE/$VERSION/build/libs/" \
        --include "*.jar" --exclude "*"

    # Verify jar integrity
    JAR=$(find "$WORKSPACE/$VERSION/build/libs/" -name "*.jar" ! -name "*-sources.jar" ! -name "*-dev.jar" | head -1)
    if [[ -z "$JAR" ]]; then
        echo "[ERROR] No jar found after retrieval."
        exit 1
    fi

    if ! jar -tf "$JAR" > /dev/null 2>&1; then
        echo "[ERROR] Jar structural integrity check failed: $JAR"
        exit 1
    fi

    echo "[SUCCESS] Build complete: $JAR"

else
    # Local build for all other versions
    echo "[LOCAL] Building $VERSION locally on Dev Panel..."
    cd "$WORKSPACE/$VERSION"
    ./gradlew build
    echo "[SUCCESS] Local build complete."
fi
