#!/bin/sh

PATH=/bin:/sbin:/usr/bin:/usr/sbin
NAME=$(basename $0)

print() { echo "## $1"; logger -t $NAME "$1"; [ x$2 = x ] || [ x$2 = x0 ] || exit $2; }

finish() {
    ${SUDO}sync
    if [ x$MOUNT_FLAG = xtrue ]; then
	print "Unmounting $BASE_DIR"
	${SUDO}umount $BASE_DIR
    fi
    print "$(date): End $NAME"
    END=$(date +%s)
    print "Duration: $((END-START)) seconds"
}

[ x$(whoami) = xroot ] || SUDO="sudo "

[ -e /etc/default/backup ] || print "/etc/default/backup not found" 1
. /etc/default/backup

trap finish exit

print "$(date): Begin $NAME"
START=$(date +%s)

if [ x$BASE_DIR != x ] && grep -sq $BASE_DIR /etc/fstab && ! grep -sq $BASE_DIR /proc/mounts; then
    ${SUDO}[ -d $BASE_DIR ] || print "Not a directory: $BASE_DIR" 1
    print "Mounting $BASE_DIR"
    ${SUDO}mount $BASE_DIR || print "Couldn't mount $BASE_DIR" 1
    MOUNT_FLAG=true
fi

${SUDO}[ -d "$SRC_DIR" ] || print "Not a directory: $SRC_DIR" 1
${SUDO}[ -d "$DST_DIR" ] || print "Not a directory: $DST_DIR" 1

if [ x$BASE_DIR = x ]; then
    EXCLUDE="$DST_DIR $EXCLUDE"
else
    EXCLUDE="$BASE_DIR $EXCLUDE"
fi
for i in $EXCLUDE; do EXCLUDES="$EXCLUDES --exclude=$i"; done

case $NAME in
    backup)
	print "${SUDO}rsync $BACKUP_RSYNC_OPTS$EXCLUDES \"$SRC_DIR\" \"$DST_DIR\""
	${SUDO}rsync $BACKUP_RSYNC_OPTS$EXCLUDES "$SRC_DIR" "$DST_DIR"
	for x in $EXCLUDE; do
	    [ -e "$DST_DIR$x" ] || [ -d "$DST_DIR$x" ] || ${SUDO}mkdir -p "$DST_DIR$x" 2>/dev/null
	    [ x$x != x/tmp ] || ${SUDO}chmod 1777 "$DST_DIR$x"
	done
    ;;
    restore)
	print "${SUDO}rsync $RESTORE_RSYNC_OPTS$EXCLUDES \"$DST_DIR\" \"$SRC_DIR\""
	${SUDO}rsync $RESTORE_RSYNC_OPTS$EXCLUDES "$DST_DIR" "$SRC_DIR"
	for x in $EXCLUDE; do
	    [ -e "$SRC_DIR$x" ] || [ -d "$SRC_DIR$x" ] || ${SUDO}mkdir -p "$SRC_DIR$x" 2>/dev/null
	    [ x$x != x/tmp ] || ${SUDO}chmod 1777 "$SRC_DIR$x"
	done
    ;;
esac

exit 0
