#!/bin/bash

# this script creates tar.bz2 archives and places them in a backup folder ordered by date
# where the latest is linked to a folder called "current"
# DEPENDS: bunzip2 ncftp (for ncftp create a bookmark with saved password)
# TODO: - simplify ftp uploading
# - do something about scp/rsync maybe
# AUTHOR: Emmanuel REVAH manu-AT-manurevah.com http://manurevah.com/
# i'm not sure about a licence so whatever, just don't sue me.. . ... :]
# \o/

logger "backup script: started"

DATE=$(date +%a_%d_%b_%Y_%Hh%Mm%S)
MONTH=$(date +%B_%Y)


########### configuration options ##############

# where we keep all the backups
BACKUPROOT="/home/backup/mybackup"
BACKUP="${BACKUPROOT}/${MONTH}/backup_${DATE}/"

# how many days worth of backups do we need to keep ?
DAYS="5"

# folders to backup: space separated values
BACKUPDIRS="/etc /var/log"
BACKUPDIRS=`ls -d ${BACKUPDIRS}`

# ncftp (create a bookmark with saved password)
# you will also need a file with ftp commands in /root/ftpcommands mine contains:
# cd backup
# rm -rf current
# put -r /home/backup/current
# quit

NCFTPBOOKMARK="ftpbookmark"

# either place a file containing ONLY the password in clear text (chmod 600 and chown root of course)
# or just replace the password here
MYSQL_USER_PASS="--user=root --password=`cat /root/.sqlpasswd`"

############ end of configuration ################


# cleanup up the "current" folder and link the new one
rm -f ${BACKUPROOT}/current
test -d ${BACKUP} || mkdir -p ${BACKUP}/mysql
ln -s ${BACKUP} ${BACKUPROOT}/current

# make some archive files
for DIRS in ${BACKUPDIRS}; do
DIRNAME=`echo ${DIRS}|sed 's/\//_/g'`
tar jcfp ${BACKUP}/${DATE}${DIRNAME}.tar.bz2 ${DIRS};
done


# mysql: please test this line to make sure it correctly lists the names of the databases
MYBASES="`ls -1 /var/lib/mysql |grep -v ib_* |grep -v debian-5.0.flag | grep -v mysql_upgrade_info`"
for DBS in ${MYBASES};do
mysqldump --databases ${DBS} ${MYSQL_USER_PASS} > ${BACKUP}/${DATE}_${DBS}.sql
done
logger "backup script: local backup done :]"

ncftp ${NCFTPBOOKMARK} < /root/ftpcommands
logger "backup script: upload current backup to ${NCFTPBOOKMARK}"

# erase older data
find ${BACKUPROOT} -type f -mtime +${DAYS} -exec rm -rf {} \;
rmdir -p ${BACKUPROOT}/*/*/*

logger "backup script: removed backups older than ${DAYS} days"

exit
