#!/bin/bash

# Script to compile all Lua files to LuaJIT bytecode
# Usage: ./compile_lua.sh

# Set paths
LUALIB_DIR="/usr/local/openresty/lualib"
LUAJIT_BIN="/usr/local/openresty/luajit/bin/luajit"

# Check if LuaJIT exists
if [ ! -x "$LUAJIT_BIN" ]; then
    echo "Error: LuaJIT not found at $LUAJIT_BIN"
    echo "Trying alternative path..."
    LUAJIT_BIN="luajit"
    if ! command -v $LUAJIT_BIN &> /dev/null; then
        echo "Error: LuaJIT not found in PATH either"
        exit 1
    fi
fi

echo "Using LuaJIT: $LUAJIT_BIN"
echo "Compiling Lua files in: $LUALIB_DIR"

# Function to compile a single Lua file
compile_lua_file() {
    local lua_file="$1"
    local ljbc_file="${lua_file%.lua}.ljbc"
    
    echo "Compiling: $lua_file"
    
    # Compile the Lua file to bytecode
    # -b: compile to bytecode
    # -s: strip debug info (optional, makes files smaller)
    if $LUAJIT_BIN -b -s "$lua_file" "$ljbc_file" 2>/dev/null; then
        echo "  ✓ Created: $ljbc_file"
        return 0
    else
        echo "  ✗ Failed to compile: $lua_file"
        return 1
    fi
}

# Counter for statistics
total_files=0
compiled_files=0
failed_files=0

# Find and compile all Lua files
echo "Starting compilation..."
echo "========================"

while IFS= read -r -d '' lua_file; do
    ((total_files++))
    if compile_lua_file "$lua_file"; then
        ((compiled_files++))
    else
        ((failed_files++))
    fi
done < <(find "$LUALIB_DIR" -name "*.lua" -type f -print0)

echo "========================"
echo "Compilation complete!"
echo "Total files: $total_files"
echo "Successfully compiled: $compiled_files"
echo "Failed: $failed_files"

# Check if nginx needs to be reloaded
if [ $compiled_files -gt 0 ]; then
    echo ""
    echo "Bytecode files created. You may need to:"
    echo "1. Update nginx.conf to include .ljbc files in lua_package_path"
    echo "2. Reload nginx: nginx -s reload"
fi 