Any idea what could I do, or how could this be scripted to have a delay after losing the connection on when the safe mode reverts the changes to the settings?
Look at scheduled scripts. On the remote end, you write a script which sets the items you are going to change back to their current values, and use a scheduler to run it at a certain time in future. Then you make the changes at the remote end first, and then on the local one. If you manage to connect to the remote device after the changes, you remove the scheduler item and the new configuration stays; if you fail to connect, you simply wait until the scheduled time (and revert the changes on the local side in the meantime) and then you'll be able to try again.
Of course debug every step first:
- create and schedule a test script doing something non-destructive like adding a global variable
- create and run the script that actually restores the current configuration by hand while in safe mode (so that if that script does something wrong, safe mode saves you)