#!/usr/bin/env bash
# build.sh — build ChatChat-fork JAR for racked.ru
# racked.ru / 2026-05-07
#
# Reproducible build via podman + temurin:21-jdk. Output: ChatChat-1.0.0-SNAPSHOT-racked-1.jar.
# The JAR is gitignored — re-run this script if the staging dir is missing it.
#
# Build target: HelpChat/ChatChat upstream main @ HEAD-of-clone-time, with a tiny
# patch noting 1.21.11 runtime is verified (apiVersion stays 1.21.4 since that's
# Bukkit's MIN-floor hint, not the runtime target).

set -euo pipefail

WORKDIR="${WORKDIR:-/tmp/chatchat-build}"
STAGING_DIR="$(cd "$(dirname "$0")/.." && pwd)"
OUT_DIR="${STAGING_DIR}/build"

if [[ -d "$WORKDIR/.git" ]]; then
  echo "=== updating existing clone in $WORKDIR ==="
  git -C "$WORKDIR" fetch origin
  git -C "$WORKDIR" checkout main
  git -C "$WORKDIR" reset --hard origin/main
else
  echo "=== fresh clone into $WORKDIR ==="
  rm -rf "$WORKDIR"
  git clone https://github.com/HelpChat/ChatChat.git "$WORKDIR"
fi

# Patch: annotate apiVersion line (no functional change, just records that 1.21.11 is verified).
if ! grep -q "racked.ru note" "$WORKDIR/plugin/build.gradle.kts"; then
  sed -i 's|apiVersion = "1.21.4"|apiVersion = "1.21.4" // racked.ru note: bukkit api floor; runtime 1.21.11 verified|' "$WORKDIR/plugin/build.gradle.kts"
fi

echo "=== running gradle shadowJar inside temurin:21-jdk ==="
podman run --rm \
  --userns=keep-id \
  -v "$WORKDIR":/work:Z \
  -w /work \
  -e BUILD_NUMBER=racked-1 \
  docker.io/library/eclipse-temurin:21-jdk \
  bash -c "bash gradlew clean shadowJar"

JAR_BUILT=$(find "$WORKDIR/plugin/build/libs" -name 'ChatChat-*-racked-*.jar' -type f | head -1)
test -f "$JAR_BUILT" || { echo "build failed: no jar produced"; exit 1; }

mkdir -p "$OUT_DIR"
cp -f "$JAR_BUILT" "$OUT_DIR/"
echo ""
echo "=== built: $OUT_DIR/$(basename "$JAR_BUILT") ($(du -h "$JAR_BUILT" | cut -f1)) ==="
ls -lh "$OUT_DIR"/*.jar
