#!/bin/bash

####################################################
# Backup script to backup home, etc, usr and var to hotpluggable disk
# Copyright (C) 2007,2008 Pete Boyd
# Version: 0.3.0
# Email: inkwire-at-thegoldenear-dot-org
# Web: http://thegoldenear.org/toolbox/unices/
####################################################



##################################################################
backup()
##################################################################
{
  # Copy those files that have not changed since last backup;
  # standard output goes to a log file;
  # standard error is sent to same place as standard output.

  # /home
  mkdir /media/backup/home
  cp /home/* /media/backup/home/ --archive --update > /var/log/hotswap-backup/backup-home-`date +%F`-`date +%H`-`date +%M`-`date +%S` 2>&1

  # /etc
  mkdir /media/backup/etc
  cp /etc/* /media/backup/etc/ --archive --update > /var/log/hotswap-backup/backup-etc-`date +%F`-`date +%H`-`date +%M`-`date +%S` 2>&1

  # /usr
  mkdir /media/backup/usr
  cp /usr/* /media/backup/usr/ --archive --update > /var/log/hotswap-backup/backup-usr-`date +%F`-`date +%H`-`date +%M`-`date +%S` 2>&1

  # /var
  mkdir /media/backup/var
  cp /var/* /media/backup/var/ --archive --update > /var/log/hotswap-backup/backup-var-`date +%F`-`date +%H`-`date +%M`-`date +%S` 2>&1

  # Unmount disk so that it can be unplugged and taken away
  umount /media/backup
}
##################################################################



# Create directory to save log files in if it doesn't already exist
if ! [ -d /var/log/hotswap-backup ]
then
 mkdir /var/log/hotswap-backup
fi


# If disk isn't mounted then try to mount it.
# If it mounts OK then do the backup, otherwise write to a log file.
# If disk is already mounted then do the backup.

# (if try to backup when device not mounted it will write to /media/backup, which, 
# when unmounted, probably lives in / and so could fill up the disk!)

if ! mount | grep "on /media/backup type" > /dev/null

then

 # If disk check above showed disk _wasn't_ mounted then try to mount it
 # If the disk doesn't mount OK the reason is written to the log file
 if mount /media/backup > /var/log/hotswap-backup/backup-general-`date +%F`-`date +%H`-`date +%M`-`date +%S` 2>&1

 then

  # If disk mounted OK above then do the backup
  backup

 fi

else

 # If disk check above showed disk _was_ mounted then don't try to mount it, just do the backup
 backup

fi


exit 0

