#!/bin/bash
set -e

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

# Create bin directory if it doesn't exist
mkdir -p "$EXTENSION_DIR/bin"

# Determine the binary name based on the current platform
case "$(uname -s)" in
    Linux*)     BINARY_NAME="wasot-lsp-linux";;
    Darwin*)    BINARY_NAME="wasot-lsp-mac";;
    MINGW*|CYGWIN*|MSYS*)  BINARY_NAME="wasot-lsp-win.exe";;
    *)          echo "Unknown platform: $(uname -s)"; exit 1;;
esac

echo "Building wasot-lsp for current platform..."
cd "$PROJECT_ROOT"
cargo build --release --bin wasot-lsp

# Copy binary to extension's bin directory
echo "Copying binary to $EXTENSION_DIR/bin/$BINARY_NAME"
if [[ "$(uname -s)" == MINGW* ]] || [[ "$(uname -s)" == CYGWIN* ]] || [[ "$(uname -s)" == MSYS* ]]; then
    cp "$PROJECT_ROOT/target/release/wasot-lsp.exe" "$EXTENSION_DIR/bin/$BINARY_NAME"
else
    cp "$PROJECT_ROOT/target/release/wasot-lsp" "$EXTENSION_DIR/bin/$BINARY_NAME"
    chmod +x "$EXTENSION_DIR/bin/$BINARY_NAME"
fi

echo "Packaging extension..."
cd "$EXTENSION_DIR"
npx @vscode/vsce package

echo "Done! Extension package created."
