#!/bin/sh
PATH=/bin/:/usr/bin:/usr/local/bin

#set -x

# use "." instead of ":" between hours and minutes because
# filenames with : are mangled over SMB.
today=`date '+%Y-%m-%dT%H.%M'`

cd /backup/ || exit 1

# remove oldest backup if disk fills up
bpct() {
    df . | sed -n -e 's/.* \([0-9][0-9]*\)%.*/\1/' -e '/^[0-9]/p'
}
ipct() {
    df -i . | sed -n -e 's/.* \([0-9][0-9]*\)%.*/\1/' -e '/^[0-9]/p'
}
cleanup() {
    while [ "`bpct`" -ge 90 -o "`ipct`" -ge 90 ]
    do
	oldest=`ls -d ????-??-??T??.?? | head -1`
	echo "`bpct` `ipct`: removing $oldest"
	if [ -z "$oldest" ]
	then
	    echo "disk almost full and nothing to delete" >&2
	    exit 1
	fi
	rm -rf "$oldest"
    done
}

# link yesterday's backup to today's

makelinks() {
    yesterday=`ls -d ????-??-??T??.?? | tail -1`

    if [ -z "$yesterday" ]
    then
	mkdir -p $today
    elif [ "$yesterday" != "$today" ]
    then
	cp -a --link $yesterday $today
    else
	: 
    fi
}

# replace changed files

backup_local() {
    echo "`isodate`: backup_local"
    rsync -a --delete --delete-excluded \
	--exclude /proc --exclude /backup --exclude /mnt \
	--exclude /n \
	/ ./$today/`hostname -f`/
}

backup_local2() {
    src="$1"
    dst="$2"
    rsync -a --stats --delete --exclude /proc --exclude /backup "$src" "./$today/$dst"
}

backup_ssh() {
    host="$1"
    echo "`isodate`: backup_ssh $host"
    rsync --rsh=ssh -a --delete --exclude /proc "$host:/" "./$today/$host/"
}

backup_ssh_dir() {
    host="$1"
    dir="$2"
    echo "`isodate`: backup_ssh_dir $host $dir"
    mkdir -p "$today/$host/$dir/"
    rsync --rsh=ssh -a --delete "$host:$dir/" "./$today/$host/$dir/"
}

cleanup

makelinks

#cleanup; backup_local
#cleanup; backup_ssh dialog.wsr.ac.at
#cleanup; backup_ssh parsifal.wsr.ac.at
#cleanup; backup_ssh eldil.wsr.ac.at
#cleanup; backup_ssh_dir merkur.wsr.ac.at /home
#cleanup; backup_ssh_dir merkur.wsr.ac.at /etc
#cleanup; backup_local2 /nfs/wsrspa/A0/users/ wsrspa.users/
