#!/bin/sh

RUN=/etc/.autobackup
RUNAS=someuser
LOCK=/var/run/backup-running
EMAIL=my@email.address
DEV=/dev/travelstar
DIR=/mnt/travelstar
DIRLIST="/etc /raid"
HOST=$(hostname)
MAILFILE=/tmp/.autobackup.$$

# If the $RUN file does not exist, we do not run.
# That makes restoring files a bit easier.
if [ ! -f "${RUN}" ]; then
    exit 0;
fi

# Lock exists, we're already running!
#
if [ -f "${LOCK}" ]; then
    exit 0;
fi

# Check for mailx, we need it
#
if [ ! -x /usr/bin/mail ]; then
    echo "You need mailx";
    exit 1;
fi

# Lock!
touch "${LOCK}"

# Does the disk device exist?
#
if [ ! -b "${DEV}" ]; then
    /bin/rm -f "${LOCK}"
    exit 1
fi

# Create a directory to mount the disk on, exit if fail.
#
mkdir ${DIR} || (/bin/rm -f  "${LOCK}" && exit 1)

# Mount it or fail.
#
mount -t ext3 ${DEV} ${DIR} || (/bin/rm -f  "${LOCK}" && exit 1)

# Create a blank mail message file.
#
echo > "${MAILFILE}"

# If we have a destination...
#
if [ -d ${DIR} ]; then
    # For each source directory...
    for dir in ${DIRLIST}; do
        # Flash status in Gnome.
        su - "${RUNAS}" -c "DISPLAY=:0.0 notify-send -u normal -i dialog-info 'Backup' 'Beginning backup run for ${dir}'"
	# Write log entry.
	echo "$(/bin/date +"%Y-%m-%d %H:%M:%S") -- Beginning backup run for ${dir}" >> "${MAILFILE}"
	# Create target dir.
	mkdir -p "${DIR}/${HOST}/${dir}" > /dev/null 2>&1
	# Run incremental backup and grab all output!
        /usr/bin/rdiff-backup "${dir}" "${DIR}/${HOST}/${dir}" 2>&1 >> "${MAILFILE}"
	# Write log entry.
	echo "$(/bin/date +"%Y-%m-%d %H:%M:%S") -- Completed backup run for ${dir}" >> "${MAILFILE}"
	# Flahs status in Gnome.
        su - "${RUNAS}" -c "DISPLAY=:0.0 notify-send -u normal -i dialog-info 'Backup' 'Completed backup run for ${dir}'"
	# Empty line in mail.
	echo >> "${MAILFILE}"
	# append a list of snapshots for this directory.
        /usr/bin/rdiff-backup -l "${DIR}/${HOST}/${dir}" >> "${MAILFILE}" 2>&1
	# Empty line in mail.
	echo >> "${MAILFILE}"
    done
fi

# Send the email to the specified email address, then delete it.
#
/usr/bin/mail "${EMAIL}" -s "${HOST} backup completed $(date +"%Y-%m-%d %H:%M:%S")" < "${MAILFILE}"
/bin/rm -f "${MAILFILE}"

# Unmount the disk.
#
umount "${DIR}"

# Remove mount directory.
#
rmdir "${DIR}"
/bin/rm -f "${LOCK}"

# Flash status in Gnome.
su - "${RUNAS}" -c "DISPLAY=:0.0 notify-send -u normal -i dialog-info 'Backup' 'Completed backup for ${HOST}. You may now disconnect the backup disk.'"
