#! /bin/bash
# backup from nas to /backupdisk
# root directories on NAS must exist on backupdisk or
# the corresponding share will not be backed up

NASROOT=/auto/nas

BACKUPROOT=/backupdisk

LOGGER="/usr/bin/logger"

# definitions for findNewDisk()
MASK="/dev/sd?"
TIMEOUT=30

# Waits for a new disk to be connected
# returns device path in $newDisk if success
# or times out after $TIMEOUT seconds
WaitNewDisk()
{
disks=($MASK)
newDisk=""
t=0
while [ $t -lt $TIMEOUT ]; do
	x=($MASK)
	for d in ${x[@]}; do
		if [[ ! "${disks[@]}" =~ "$d" ]];
		then
		newDisk="$d"
		sleep 2	# sleep to allow the kernel to set up the device
		return
		fi
	done
	sleep 1
	let t=t+1
done
}

#####################################################

RSYNCOPTS="--exclude-from=/usr/local/etc/rsyncExcludes.nas2backup -a -v -H --delete"

$LOGGER "starting NAS backup"
# Note: this will automount the nas disk
nasdirs=($NASROOT/*)

if ! grep -q "$NASROOT" /proc/mounts
then
	$LOGGER "$0: nas not mounted! Terminate"
	echo "exiting because of $0: nas not mounted! Terminate"
	exit
fi

if ! grep -q "$BACKUPROOT" /proc/mounts
then
	# power on backup disk
	relay 1 on
	WaitNewDisk
	if [[ "$newDisk" = "" ]];
	then
		$LOGGER "$0: backup disk failed to appear! Terminate"
		echo "exiting because of $0: backup disk failed to appear! Terminate"
		relay 1 off
		exit
	fi
	$LOGGER "$0: backup disk is $newDisk"
	# assuming ${newDisk}1 as target partition
	mount ${newDisk}1 $BACKUPROOT
	sleep 5
else
	newDisk=$(grep "/backupdisk" /proc/mounts)
	newDisk=${newDisk%%[[:digit:]] *} # remove everything after /dev/sdx
	$LOGGER "$0: using already mounted backup disk $newDisk"
fi

NASUUID=$(findmnt $NASROOT -o UUID -n)
BACKUPUUID=$(findmnt $BACKUPROOT -o UUID -n)
export NASUUID;
export BACKUPUUID;

# happens sometimes for unknown reasons
if [[ "$NASUUID" = "" ]];
then
	echo "Exiting because of NASUUID=''"
	exit
fi
if [[ "$BACKUPUUID" = "" ]];
then
	echo "Exiting because of BACKUPUUID=''"
	exit
fi

$LOGGER "Updating Media Information"
/usr/local/bin/backupUpdateMedia
# backup encrypted partition only if there exists a directory named "Backups"
if [ -d $BACKUPROOT/Backups ]; then
	$LOGGER "Backing up encrypted partition"
	/usr/local/bin/rsyncEnc.pl
	RSE=$?
	if [ "$RSE" -lt 0 ]; then
			echo "rsyncEnc.pl returned $RSE"
			exit
	fi
fi
# backup is done by separate rsyncs for each NAS root folder
# the corresponding directory must already exist on the
# backup disk or it will be skipped!
# this allows to split the backup do several disks
# e.g. one for each directory
for d in ${nasdirs[@]}
do
	d="$(basename $d)"
	if [[ -d "$BACKUPROOT/$d" ]]	# directory exists on backup disk
		then
		$LOGGER "$0: syncing $d"
		echo "*** Syncing $d"
		starttime=`date +%s`
		rsync $RSYNCOPTS $NASROOT/$d/ $BACKUPROOT/$d
		cc=$?
		endtime=`date +%s`
		duration=$((endtime-starttime))
		backupUpdateDB --srcid=$NASUUID --srcdir=$d --targetid=$BACKUPUUID --duration=$duration --result=$cc
	else
		$LOGGER "$0: skipping $d - directory does not exist on destination"
	fi
done

umount $BACKUPROOT
sync
#hdparm -qY $newDisk	# send backup disk to standby
sleep 5 # better safe than sorry...
# power off backup disk if no longer mounted
findmnt $BACKUPROOT >/dev/null || relay 1 off
$LOGGER "NAS backup complete"
