#!/bin/bash
# Enable debugging trace
# set -x
# ------ Documentation -------
# Parameters
# $1 = backup name
# $2 = Joomla PHP Code directory
# $3 = DB name
# $4 = DB user
# $5 = DB password
# $6 = FTP URL
# $7 = FTP User
# $8 = FTP Psw
# $9 = FTP remote directory where to save the file. A weekly subdirectory with the day name is automatically created.

# Sample command
# ./backup_weekly.sh test /home/CPANEL_ACCOUNT/domains/jms2win.com/subdomains/master/public_html dbname dbuser "DB-Password" ftp.yourdomain.com ftpuser ftppassword /backup/
# ./backup_weekly.sh test /home/CPANEL_ACCOUNT/domains/jms2win.com/subdomains/master/public_html dbname dbuser "DB-Password" ftp.yourdomain.com ftpuser ftppassword
# ./backup_weekly.sh test /home/CPANEL_ACCOUNT/domains/jms2win.com/subdomains/master/public_html dbname dbuser "DB-Password"

# -- Create the backup name corresponding to the day of the week
mkdir -p $PWD/weekly/`date +%A`/$1

# -- remove previous backup present in the directory
rm -f $PWD/weekly/`date +%A`/$1/*

# -- Backup DB (without locking and force to continue in case of error)
mysqldump --force --lock-tables=false -u$4 -p$5 -r$PWD/weekly/`date +%A`/$1/db_$3-`date +%d-%b-%Y-%Hh%M`.sql $3

# -- Backup PHP Code
tar -cvzf $PWD/weekly/`date +%A`/$1/sites_`date +%d-%b-%Y-%Hh%M`.tgz $2

# ----------------------------
# -- In case where you want to send the backup on another server by FTP

# Remove the previous compressed backup
rm -f $PWD/weekly/`date +%A`/$1.tgz

# Compress the backup (db + site)
tar -cvzf $PWD/weekly/`date +%A`/$1.tgz $PWD/weekly/`date +%A`/$1

# When the FTP parameters are present, Send the file by FTP
if [ $# -ge 8 ]
then
   lftp ftp://"$7":"$8"@$6 -e "mkdir -p $9/weekly/`date +%A` ; put -O $9/weekly/`date +%A` $PWD/weekly/`date +%A`/$1.tgz  ; quit"
fi
