#!/usr/bin/env bash
# ==============================================================
#  run_new.sh — Build & launch RobotControllernew
#
#  Prerequisites (must be in the same directory as this script):
#    - RobotControllernew.java
#    - jSerialComm-2.10.4.jar
#
#  Usage:
#    chmod +x run_new.sh   (first time only)
#    ./run_new.sh
# ==============================================================

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

JAVA_FILE="RobotControllernew.java"
JAR="jSerialComm-2.10.4.jar"
MAIN_CLASS="RobotControllernew"
OUT_DIR="out"

# ── Preflight checks ──────────────────────────────────────────
if [ ! -f "$JAVA_FILE" ]; then
    echo "[ERROR] $JAVA_FILE not found in $(pwd)"
    exit 1
fi

if [ ! -f "$JAR" ]; then
    echo "[ERROR] $JAR not found in $(pwd)"
    echo "        Download it from:"
    echo "        https://github.com/Fazecast/jSerialComm/releases"
    exit 1
fi

if ! command -v javac &>/dev/null; then
    echo "[ERROR] javac not found. Install a JDK (11 or higher recommended)."
    exit 1
fi

if ! command -v java &>/dev/null; then
    echo "[ERROR] java not found. Install a JRE/JDK (11 or higher recommended)."
    exit 1
fi

# ── Detect OS for classpath separator ─────────────────────────
case "$(uname -s)" in
    MINGW*|CYGWIN*|MSYS*)
        SEP=";"
        ;;
    *)
        SEP=":"
        ;;
esac

# ── Compile ───────────────────────────────────────────────────
mkdir -p "$OUT_DIR"

echo "[BUILD] Compiling $JAVA_FILE ..."
javac -cp ".${SEP}${JAR}" -d "$OUT_DIR" "$JAVA_FILE"
echo "[BUILD] Compilation successful."

# ── Run ───────────────────────────────────────────────────────
echo "[RUN]   Launching $MAIN_CLASS ..."
java --enable-native-access=ALL-UNNAMED \
     -cp "${OUT_DIR}${SEP}${JAR}" "$MAIN_CLASS"
