#!/bin/bash

export WINEPREFIX="/wine/prefix"
export WINEARCH=win32
export WINEDEBUG=-all
export DISPLAY=:99

echo "[INFO] Starting virtual X11 display on :99 (1280x720)..."
Xvfb :99 -screen 0 1280x720x24 +extension RANDR &
sleep 1

# Accept target filename as first argument
TARGET_FILENAME="${1:-target.exe}"

if [ ! -f "/input/${TARGET_FILENAME}" ]; then
    echo "[ERROR] Missing /input/${TARGET_FILENAME}"
    exit 1
fi

echo "[INFO] Preparing internal analysis environment..."
cp "/input/${TARGET_FILENAME}" "/app/ida/target.exe"

# Copy companion DLLs if provided (optional /dlls mount)
if [ -d "/dlls" ] && [ "$(ls -A /dlls 2>/dev/null)" ]; then
    echo "[INFO] Copying companion DLLs to analysis directory..."
    cp /dlls/* /app/ida/ 2>/dev/null || true
fi

echo "[INFO] Launching IDA Pro 6.6 (auto-script)..."
wine idaq.exe -A -S"extract.py" target.exe

echo "[INFO] Verifying generated artifacts..."
if [ -f "/app/ida/output.json" ]; then
    cp /app/ida/output.json /output/output.json
    echo "[SUCCESS] Static analysis completed. output.json is ready!"
    RET_CODE=0
else
    echo "[ERROR] IDAPython script failed to generate output.json"
    RET_CODE=1
fi

# Clean up temporary files inside the container before exiting
rm -f /app/ida/target.exe /app/ida/target.idb /app/ida/output.json

exit $RET_CODE
