#!/bin/bash

## Variables here...
maxdays=7		## Maximum days of history to keep...
backups_path="/backups"

function log {
	logger -i rsync_backup "$0: $1"
	echo "`date`: $1"
}

function rotate_backup() {
	local hostname="$1"
	log "$hostname: Rotating backups"
	## Delete last backup if it exists...
	if [ -d $backups_path/$hostname/$maxdays ]; then
		#rm -fR $backups_path/$hostname/$maxdays
		btrfs subvolume delete $backups_path/$hostname/$maxdays
	fi
	for ((i=$maxdays; i>=1; i--)); do
		if [ -d $backups_path/$hostname/$i ]; then
			mv $backups_path/$hostname/$i $backups_path/$hostname/$(($i + 1))
		fi
	done
	if [ -d $backups_path/$hostname/0 ]; then
		#cp -al $backups_path/$hostname/0 $backups_path/$hostname/1
		btrfs subvolume snapshot -r $backups_path/$hostname/0 $backups_path/$hostname/1
	else
		#mkdir -p $backups_path/$hostname/0
		btrfs subvolume create $backups_path/$hostname/0
	fi
}

if [ -f /tmp/rsync.lock ]; then
	echo "Error - $0 already running!"
	exit 1
fi

## Create a lock file to stop multiple instances...
touch /tmp/rsync.lock

## Run through the systems and back them up.
cd /backups/
for host in $(ls -d */); do
	host=`echo ${host%%/}`
	if [ "$host" == "archives" ]; then continue; fi
	if [ -f "$host/options" ]; then . "$host/options"; fi
	if [ -f "$host/excludes" ]; then RSYNC_OPTIONS="$RSYNC_OPTIONS --exclude-from=$host/excludes"; fi

	## Check to see if we haven't backed this host up in the past 6 hours
	mtime=`stat -c %Y $backups_path/$host/0`
	curtime=`date +%s`
	diff=$(( curtime - mtime ))
	if [ $diff -lt 21600 ]; then
		log "$host - Backed up $diff seconds ago. Skipping."
		continue
	fi

	log "$host: Started backup..."
	rotate_backup "$host" &
	log "$host: Saving file permissions..."
	timeout 60s ssh $host create_file_list 2>&1 &
	log "$host: Waiting for rotation and permissions to complete..."
	wait $(jobs -p)
	log "$host: Rotation & permissions backup completed. Starting rsync."
	#rsync -a -H --stats --no-owner --no-group --exclude=/var/log/lastlog -S --link-dest=$backups_path/$host/1 --delete --delete-excluded $RSYNC_OPTIONS $host:/ $backups_path/$host/0 2>&1
	rsync -ax -H --stats --exclude=/var/log/lastlog -S --delete --delete-excluded $RSYNC_OPTIONS $host:/ $backups_path/$host/0 2>&1
	touch -m $backups_path/$host/0
	log "$host: Backup complete..."
	RSYNC_OPTIONS=""
	echo -e "\n\n\n"
done

echo "Free Space:"
df -h

rm -f /tmp/rsync.lock
