Picade X hat shutdown functionality help needed

Hi all, I’m using a Picade X hat on a Pi4 for my arcade project. I’ve been trying to intercept the shutdown procedure to gracefully quit out of my emulator and save hiscores etc before the file system is made read only by the shutdown process. I’ve tried many scripts and systemd services but none of them seem to work for me. I’m not a linux expert by any means. I’m using the current Retropie image. When the power button is pressed to shutdown the system, what script is it calling? Can this be edited to add in a command or call to another script to shutdown my emulator properly before continuing with the shutdown process?

I think the shutdown part is done via a dtoverlay.
Then a sevice thats running in the background pulls a GPIO pin low to signal the Hat to kill the power.

@alphanumeric ,thanks for your reply. I had worked out while searching for a solution that there was an overlay monitoring GPIO 17 for a button press, but this must in turn call a script to perform the shutdown. I have successfully created a script that executes a shutdown. My test displayed a video so I would have a visual cue that something had happened. This was fine until I substituted in my code to quit out of mame and save the hi-scores. This didn’t work. After a bit of digging I found out that at the time of execution of my script, the shutdown process had made the filesystem read-only. Playing a video worked since it wasn’t trying to write anything, mame however did quit but couldn’t write out the hi-scores etc because of this. I need to interrupt the process and issue my command before this happens. Seems easier said than done I’m afraid.