#!/bin/bash
# Decompile HytaleServer.jar and copy to generated/
# Run from project root

set -e

PATCHER_DIR="vendor/hytale-server/patcher"
GENERATED_DIR="vendor/hytale-server/generated"

if [ ! -d "$PATCHER_DIR" ]; then
    echo "Error: patcher directory does not exist"
    exit 1
fi

if [ ! -d "$PATCHER_DIR/venv" ]; then
    echo "[decompile] Creating venv..."
    python3 -m venv "$PATCHER_DIR/venv"
fi

echo "[decompile] Activating venv..."
source "$PATCHER_DIR/venv/bin/activate"

if [ -f "$PATCHER_DIR/requirements.txt" ]; then
    echo "[decompile] Installing requirements..."
    pip install -q -r "$PATCHER_DIR/requirements.txt"
fi

echo "[decompile] Setting up HYTALESERVER_JAR_PATH..."
export HYTALESERVER_JAR_PATH="$(pwd)/vendor/hytale-server/Server/HytaleServer.jar"

echo "[decompile] Cleaning previous work..."
rm -rf "$PATCHER_DIR/work"
rm -rf "$PATCHER_DIR/hytale-server"

echo "[decompile] Running patcher setup..."
cd "$PATCHER_DIR"
python run.py setup

echo "[decompile] Copying decompiled sources to generated/..."
cd -
rm -rf "$GENERATED_DIR"
cp -r "$PATCHER_DIR/work/decompile" "$GENERATED_DIR"

echo "[decompile] Removing fastutil..."
rm -rf "$GENERATED_DIR/com/hypixel/fastutil"

echo "[decompile] Done. Decompiled sources at: $GENERATED_DIR"
