Starting dnsmasq causes all connections to be reset. That’s what the script seems to stop. I have moved that to the end of the script and added a 15 second delay before rebooting the RPi.
Writing these installation scripts is almost as involved as writing the main applications.