[361] | 1 | #!/bin/sh
|
---|
| 2 | #
|
---|
| 3 | # Shutdown system if it has been idle for 1 hour and no active users are logged
|
---|
| 4 | # in.
|
---|
| 5 | #
|
---|
| 6 | # Usage: This script is mainly used on a home server used for building FreeBSD
|
---|
| 7 | # World and kernels. As soon it is done it can shutdown if not being used
|
---|
| 8 | # anymore. The system has Wake-On-Lan support and can thus be activated again
|
---|
| 9 | # from remote.
|
---|
| 10 | #
|
---|
| 11 | # Please run from cron every CRON_INTERVAL minutes:
|
---|
| 12 | # */5 * * * * * /usr/local/bin/power-saver
|
---|
| 13 | #
|
---|
| 14 | # Rick van der Zwet <info@rickvanderzwet.nl>
|
---|
| 15 | #
|
---|
| 16 |
|
---|
| 17 | CRON_INTERVAL=5
|
---|
| 18 | MAX_LOAD=0.10
|
---|
| 19 | MAX_IDLE=60
|
---|
| 20 |
|
---|
| 21 | # Stored as <epoch> <load>
|
---|
| 22 | DAT_FILE='/tmp/power-saver.dat'
|
---|
| 23 |
|
---|
| 24 | # Current values
|
---|
| 25 | EPOCH=`date "+%s"`
|
---|
| 26 | LOAD_15=`sysctl vm.loadavg | awk '{print $5}'`
|
---|
| 27 |
|
---|
| 28 | # Empty file needs to be created and filled
|
---|
| 29 | echo "$EPOCH $LOAD_15" >> $DAT_FILE || exit 1
|
---|
| 30 |
|
---|
| 31 | # Check if countdown has already been started
|
---|
| 32 | ps -x | grep -q '[0-9] shutdown' && exit 0
|
---|
| 33 |
|
---|
| 34 | # Check if all users are no longer active
|
---|
| 35 | SHORTEST_IDLE=`w -ih | awk '{print $5}' | head -1`
|
---|
| 36 | # Hack to make sure time is always in minutes
|
---|
| 37 | SHORTEST_IDLE_IN_MIN=`echo $SHORTEST_IDLE | awk -F: '{if (NF > 1){print $1 * 60 + $2}else{print $1}}'`
|
---|
| 38 | if [ -z "$SHORTEST_IDLE_IN_MIN" ]; then
|
---|
| 39 | # No users are currently logged in
|
---|
| 40 | continue
|
---|
| 41 | elif [ "$SHORTEST_IDLE_IN_MIN" = "-" ]; then
|
---|
| 42 | # User is still active an minute ago
|
---|
| 43 | exit 0
|
---|
| 44 | elif [ $SHORTEST_IDLE_IN_MIN -le $MAX_IDLE ]; then
|
---|
| 45 | # User is still active less than MAX_IDLE ago
|
---|
| 46 | exit 0
|
---|
| 47 | fi
|
---|
| 48 |
|
---|
| 49 | # Count the amount entries we are current on our way
|
---|
| 50 | IDLE_COUNTS=`awk -vMAX_LOAD=$MAX_LOAD -vMAX_IDLE=$MAX_IDLE -vEPOCH=$EPOCH \
|
---|
| 51 | 'BEGIN{MIN_TIME=EPOCH-MAX_IDLE;s=0}{if ($1 > MIN_TIME && $2 > MAX_LOAD){s += 1}}END{print s}' $DAT_FILE`
|
---|
| 52 |
|
---|
| 53 | # We are idle for over $MAX_IDLE time, starting shutdown
|
---|
| 54 | if [ $IDLE_COUNTS -gt `expr $MAX_IDLE / $CRON_INTERVAL` ]; then
|
---|
| 55 | echo shutdown -p "+15" "Cancel: sudo killall -SIGTERM shutdown"
|
---|
| 56 | fi
|
---|