Skip to content

Instantly share code, notes, and snippets.

@nonkronk
Created April 19, 2023 15:21
Show Gist options
  • Save nonkronk/384a86986a41064211876f9ffed71812 to your computer and use it in GitHub Desktop.
Save nonkronk/384a86986a41064211876f9ffed71812 to your computer and use it in GitHub Desktop.
Script to auto-shutdown UNRAID after x minutes of power loss
#!/bin/bash
#set which hosts will be checked
CHECKHOST1="10.0.0.100"
CHECKHOST2="10.0.0.100"
MAX_FAILS=10
FAILCOUNT=0
GLOBALFAILCOUNT=0
PERIOD=30
#start main loop
echo "Power failure monitoring started @ $(date)" >> /mnt/disks/ua_docker/powerlog.log
while :
do
echo "PowerLoss Detection : FAILURE= $FAILCOUNT/$MAX_FAILS ($CHECKHOST1 $CHECKHOST2) TotalErros= $GLOBALFAILCOUNT"
if [ "$FAILCOUNT" -gt "0" ]
then
beep -f $((200*$FAILCOUNT)) -r $FAILCOUNT
fi
if [ "$FAILCOUNT" -gt "$MAX_FAILS" ]
then
echo "We reached Max Failures , System Shutdown will start after notifications are fired"
/usr/local/emhttp/webGui/scripts/notify -e "Power failure detected" -s "Power seems to be offline" -d "Power failure" -i "alert" -m "Power failure detected, poweroff is in order"
echo "Shutdown due to power failure $(date)" >> /mnt/disks/ua_docker/powerlog.log
sleep 2
/sbin/poweroff
fi
sleep $PERIOD
echo "$(date) - Running PowerLoss Detection Routine, trying to reach $CHECKHOST1"
var=$(ping $CHECKHOST1 -c 5 -W 5 | grep "0 received")
if [ -z "$var" ]
then
if [ "$FAILCOUNT" -eq "0" ]; then
echo "$(date) - power is A-OK"
else
echo "$(date) - power is BACK sending notification"
/usr/local/emhttp/webGui/scripts/notify -e "Power is back" -s "Power returned" -d "Power is back" -i "normal" -m "Power is back after $FAILCOUNT checks"
beep -f 784 -r 3 -l 100
sleep .1
beep -f 784 -l 600
beep -f 622 -l 600
beep -f 698 -l 600
beep -f 784 -l 200
sleep .2
beep -f 698 -l 200
beep -f 784 -l 800
fi
FAILCOUNT=0
else
echo "$var"
echo "$(date) - we couldn't reach $CHECKHOST1"
echo "$(date) - Trying $CHECKHOST2"
#if we can't reach the 2nd host then we're in trouble increment a counter
var=$(ping $CHECKHOST2 -c 5 -W 5 | grep "0 received")
if [ -z "$var" ]
then
echo "$var"
echo "we could reach $CHECKHOST2 , standing by..."
else
echo "$var"
echo "$(date) - we couldn't reach $CHECKHOST2"
FAILCOUNT=$((FAILCOUNT + 1))
GLOBALFAILCOUNT=$((GLOBALFAILCOUNT+ 1))
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment