Safely terminate on SIGTERM

I just moved the last bit of the script to a function that will be executed on EXIT, so we don't miss it in case of a signal.