#!/bin/sh
#
# Backup script using hardlink and rsync

LOGDIR=/var/log/hlbackup
BASE=/backup
TODAY=`date +%Y/%m/%d`
RSYNC='/usr/bin/rsync -aqHS --numeric-ids --delete --delete-excluded'
NAME=hlbackup

# lower priority
which ionice > /dev/null && ionice -c 3 -p $$
which renice > /dev/null && renice 19 -p $$ >/dev/null

test -f /etc/default/hlbackup && . /etc/default/hlbackup

errormsg() {
	local msg=$1

	echo "backup failed: $msg" 1>&2
	echo "backup failed: $msg" | logger -i -t $NAME -p local0.err
}

backup() {
	local host=`echo $1 | sed -e 's/:.*//'`
	if [ -z "$host" ]; then
		errormsg "$src: could not find target hostname"
		return
	fi
	logfile=$LOGDIR/$host/`basename $1`.log
	src=`echo $1 | sed -e 's/\/*$//'`
	if [ -z "$src" ]; then
		errormsg "could not find source (e.g. hostname:/target/directory)"
		return
	fi
	srcname=`basename $src`
	shift

	# prepare backup
	mkdir -p `dirname $logfile`
	savelog -q -m 0640 -u root -g adm -t $logfile
	test "`hostname`" = "$host" && src=`echo $src | sed -e 's/^[^/]*//'`
	if [ ! -d "$BASE/$host" -o ! -w "$BASE/$host" ]; then
		errormsg "$src: could not write to directory: $BASE/$host"
		return
	fi
	mkdir -p ${BASE}/${host}/${TODAY}

	# find "--link-dest" argument
    if [ -d "${BASE}/${host}/latest/$srcname" -a \
	     ! "${BASE}/${host}/latest/$srcname" -ef "${BASE}/${host}/${TODAY}/$srcname" ]; then
		linkdest=--link-dest=${BASE}/${host}/latest/$srcname/
	else
		linkdestdir=`find ${BASE}/${host}/ -maxdepth 4 -type d -path "${BASE}/${host}/????/??/??/$srcname" | sort -n | tail -1`
		if [ -n "$linkdestdir" -a \
		     ! "${BASE}/${host}/latest/$srcname" -ef "$linkdestdir" ]; then
			linkdest=--link-dest=$linkdestdir/
		else
			linkdest=""
		fi
	fi

	# run backup
	echo "starting backup: $src" | logger -i -t $NAME -p local0.info
	$RSYNC --log-file=$logfile $linkdest $src/ ${BASE}/${host}/${TODAY}/$srcname/ $*
	if [ $? = 0 -o $? = 24 ]; then
		rm -f $BASE/$host/latest
		ln -sf $TODAY $BASE/$host/latest
		echo "backup completed: $src" | logger -i -t $NAME -p local0.info
	else
		errormsg $src | logger -i -t $NAME -p local0.err
	fi
}

if [ -n "$1" ]; then
	if echo "$1" | grep -vq :\/; then
		echo "Usage: $0 hostname:/dirname" 1>&2
		exit 1
	fi
	backup $*
else
    . /etc/hlbackup/run-backup
fi

# vim: set ts=4:sw=4:
