#!/bin/sh

# based on various posts in http://www.synology-forum.de/showthread.html?8769-DS-herunterfahren-wenn-kein-Client-mehr-vorhande

# last edits by Dominik Deobald
# http://blog.deobald.org/

PINGHOSTS=""
ACTIVEHOSTS="192.168.0.10 192.168.0.11"
RUNNINGPROC=""

#LOGFILE=""
LOGFILE=/dev/null
COUNTFILE=/tmp/unused-counter

log() {
	echo `date +%c` $1 >> $LOGFILE
}

ONLINE=0
DOWNLOAD=0
ACTIVE=0
BACKUP=0
PROCESS=0
LIFESIGNS=0

if [ "$(pidof synolocalbkp)" ]; then
	BACKUP=1
	log "Backup is running"
fi

for host in $PINGHOSTS ; do
	if ping -c 3 -w 1 $host > /dev/null; then
		ONLINE=1
		log "$host isn't offline"
	fi
done

if netstat | grep 'http' | grep -v ccsleeds > /dev/null; then
	DOWNLOAD=1
	log "currently downloading"
fi

for host in $ACTIVEHOSTS ; do
	if netstat -n | grep ' '$host':.*ESTABLISHED' > /dev/null; then
		ACTIVE=1
		log "$host currently accessing NAS"
	fi
done

for process in $RUNNINGPROC ; do
	if (ps aux | grep $process | grep R | grep -v grep) ; then
		PROCESS=1
		log "Process $process is running"
	fi
done

if [ $BACKUP -eq 0 ] && [ $ONLINE -eq 0 ] && [ $DOWNLOAD -eq 0 ] && [ $ACTIVE -eq 0 ] && [ $PROCESS -eq 0 ] && [ $LIFESIGNS -eq 0 ] ; then
	echo >>$COUNTFILE
	COUNTER=`ls -la $COUNTFILE | awk '{print $5}'`
	log "NAS has been idle for $COUNTER checks"

	if [ $COUNTER -gt 10 ]; then
		log "shutdown Diskstation"
		rm $COUNTFILE
		/sbin/poweroff
	fi
else
	[ -f $COUNTFILE ] && rm $COUNTFILE
fi
