#!/bin/bash

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

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

# Ensure required input files exist in the mounted volumes
if [ ! -f "/input/${TARGET_FILENAME}" ]; then
    echo "[ERROR] Missing /input/${TARGET_FILENAME}"
    exit 1
fi

if [ ! -f "/app/ida/extract.idc" ]; then
    echo "[ERROR] Missing /app/ida/extract.idc"
    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

# Force IDA to suppress all initial compiler dialogs and welcome screens
echo -e "ASK_COMPILER = NO\nASK_EXIT = NO\nDISPLAY_WELCOME = NO" >> /app/ida/ida.cfg

echo "[INFO] Launching IDA Pro 5 in headless batch mode..."
xvfb-run -a wine idag.exe -A -c -S"extract.idc" "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] IDC 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
