What exactly happens when the power button is pressed to shutdown on Picade X HAT

Can anyone help me out by explaining what happens when the power button on a Picade X HAT is pressed to shutdown the system. What script is called and is it possible to intercept what the overlay is doing? I want to run a command after the button is pressed but before shutdown which will save a file/files to the SD card. This needs to be done before the shutdown process makes the file system read only, hence preventing the file from being written.