// Ghidra headless script (Java): apply Blutter function boundaries + names, then decompile targets.
import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.FunctionManager;
import ghidra.program.model.symbol.SourceType;
import ghidra.app.cmd.disassemble.DisassembleCommand;
import ghidra.app.cmd.function.CreateFunctionCmd;
import ghidra.app.decompiler.DecompInterface;
import ghidra.app.decompiler.DecompileResults;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;

public class ApplyBlutterAndDecompile extends GhidraScript {
    static final long OFF = 0x100000L; // Ghidra rebases the ELF by +0x100000
    Address A(String h) { return toAddr(Long.parseLong(h.substring(2), 16) + OFF); }

    @Override
    public void run() throws Exception {
        FunctionManager fm = currentProgram.getFunctionManager();

        ArrayList<String[]> funcs = new ArrayList<>();
        try (BufferedReader r = new BufferedReader(new FileReader("/tmp/blutter_out/gh_funcs.txt"))) {
            String ln;
            while ((ln = r.readLine()) != null) {
                ln = ln.trim(); if (ln.isEmpty()) continue;
                funcs.add(ln.split(","));
            }
        }
        ArrayList<String[]> names = new ArrayList<>();
        try (BufferedReader r = new BufferedReader(new FileReader("/tmp/blutter_out/gh_names.txt"))) {
            String ln;
            while ((ln = r.readLine()) != null) {
                if (ln.isEmpty()) continue;
                int t = ln.indexOf('\t'); if (t < 0) continue;
                names.add(new String[]{ln.substring(0, t), ln.substring(t + 1)});
            }
        }
        println("[*] funcs=" + funcs.size() + " names=" + names.size());

        int made = 0;
        for (String[] fe : funcs) {
            try {
                Address a = A(fe[0]);
                if (fm.getFunctionAt(a) != null) continue;
                new DisassembleCommand(a, null, true).applyTo(currentProgram, monitor);
                boolean ok = new CreateFunctionCmd(a).applyTo(currentProgram, monitor);
                if (ok) made++;
                if (made > 0 && made % 20000 == 0) println("  .. created " + made + " functions");
            } catch (Exception ex) {}
        }
        println("[*] created " + made + " functions");

        int applied = 0;
        for (String[] ne : names) {
            try {
                Address a = A(ne[0]);
                Function fn = fm.getFunctionAt(a);
                if (fn != null) fn.setName(ne[1], SourceType.USER_DEFINED);
                else createLabel(a, ne[1], true);
                applied++;
            } catch (Exception ex) {}
        }
        println("[*] applied " + applied + " names");

        DecompInterface di = new DecompInterface();
        di.openProgram(currentProgram);
        String[] targets = {"0x33b0d1c"}; // setSuperCharge
        for (String tgt : targets) {
            Function fn = fm.getFunctionAt(A(tgt));
            println("\n================ DECOMPILE " + tgt + " (" + (fn != null ? fn.getName() : "?") + ") ================");
            if (fn == null) continue;
            DecompileResults res = di.decompileFunction(fn, 120, monitor);
            if (res.decompileCompleted()) println(res.getDecompiledFunction().getC());
            else println("decompile failed: " + res.getErrorMessage());
        }
    }
}
