I stumbled across this entirely by accident looking for the proper shutdown command but came up with the same idea you did. I installed a cheap UPS for a customer to prevent their server from shutting down abruptly as it killed 1 drive already. Here's the code that I used chatgpt to help make, instead of pinging a device on the network I have it ping the gateway itself which works out perfectly here since their network isn't on a battery backup. If you want to use this replace the IP with your gateway and desired timings.
#!/bin/bash
while true; do
printf "%s" "Checking local LAN gateway @ 192.168.86.1..."
if ping -c 1 -n -w 1 192.168.86.1 &> /dev/null; then
printf "\n%s" "gateway is responding"
else
printf "\n\n------------------------------------------------------------------------"
printf "\n%s" "gateway is not responding, waiting 5 minutes before checking again..."
printf "\n------------------------------------------------------------------------\n"
# Wait for 5 minutes before checking again
sleep 300
printf "\n%s\n" "Rechecking gateway..."
if ping -c 1 -n -w 1 192.168.86.1 &> /dev/null; then
printf "\n------------------------------------------------------------------------"
printf "\n%s" "Gateway is now responding, shutdown avoided..."
printf "\n------------------------------------------------------------------------\n"
else
printf "\n------------------------------------------------------------------------"
printf "\n%s" "Gateway is still not responding after 5 minutes, shutting down..."
printf "\n------------------------------------------------------------------------\n"
powerdown
exit 1
fi
fi
# If the loop reaches here, it means the IP is now responding
printf "\n%s\n\n" "Checking again in 30 seconds..."
sleep 30
done
I also formatted it so in the logs it looks nice and pretty with good spacing for at a glance troubleshooting.