// Script to export decompiled C code for selected function from Ghidra
// @category _Reman3
// @menupath Reman3.Dump Current Function

import ghidra.app.script.GhidraScript;
import ghidra.program.model.listing.Function;
import re3lib.FunctionDumper;
import re3lib.GlobalDumper;
import re3lib.RemanConfig;
import re3lib.FunctionDatabase;

public class DumpCurrentFunction extends GhidraScript {
  @Override
  public void run() throws Exception {
    RemanConfig.INSTANCE = new RemanConfig(this);
    RemanConfig.INSTANCE.createDirectories();

    try (FunctionDatabase functionDatabase = new FunctionDatabase(this)) {
      GlobalDumper globalDumper = new GlobalDumper(this, functionDatabase);
      globalDumper.loadGlobalManifest();
      FunctionDumper functionDumper = new FunctionDumper(this, functionDatabase, globalDumper);

      Function currentFunction = getFunctionContaining(currentAddress);
      if (currentFunction != null) {
        functionDumper.dump(currentFunction);
      } else {
        println("No function found at the current address.");
      }

      if (functionDumper.createdFile)
        RemanConfig.INSTANCE.touchCMakeTimestamp();

      globalDumper.dumpGlobals();
      globalDumper.saveGlobalManifest();
    }
  }
}
