// backup a folder contains all .php files and it's mysql database. a backup.ini file is required for storing mysql root login and what folder to be backed up.
#!/bin/sh
########################################
# simple sctipt for daily / hourly backup of PHP app + Mysql DB
# Copyleft (c) Sayid Munawar. chenull@yahoo.com
# LICENSE: anyone can copy / modify / distribute. whatever lah
#
# example of workhours backup (8 am - 5 pm. Mon - Fri)
# 0 8-17 * * 1-5 /home/backup/backup.sh
#
# example of simple dayly backup ( 6 pm. Mon - Fri)
# 0 18 * * 1-5 /home/backup/backup.sh
########################################
########################################
# example of backup.ini. REMOVE ALL leading '#'s
# file must be chmod 600
#[main]
#target = /home/backup/storage
#mysql_user = root ; root can connect to any db
#mysql_pass = secret ; mysql root password
#
#[hukum]
#path = /home/hukum
#mysql_db = hukum
#
#[phpmyadmin]
#path = /home/phpmyadmin
#mysql_db = test
########################################
PATH=$PATH:/usr/bin:/bin:/usr/local/bin
inifile=`dirname $0`/backup.ini
test ! -r $inifile && echo "ERROR! backup.ini not found nor readable" && exit 1
#test apakah backup.ini bisa dibaca orang lain
echo -n `stat -c '%a' $inifile` | grep -q '[0-7]00' >/dev/null 2>&1
test $? -gt 0 && echo "ERROR! $inifile can be read by others" && exit 2
#test `stat -c '%U' $inifile` != 'root' && echo "ERROR! $inifile ownernya bukan root" && exit 3
# function to parse ini file (backup.ini)
#
# $1 -> file.ini
# $2 -> section
_parse_ini () {
if [ -z "$1" ] || [ -z "$2" ]; then return 0; fi
eval `cat $1 | \
sed -e 's/[[:space:]]*\=[[:space:]]*/=/g' \
-e 's/;.*$//' \
-e 's/[[:space:]]*$//' \
-e 's/^[[:space:]]*//' \
-e "s/^\(.*\)=\([^\"']*\)$/\1=\"\2\"/" | \
sed -n -e "/^\[$2\]/,/^\s*\[/{/^[^;].*\=.*/p;}"`
}
_parse_ini $inifile main
# coba konek
mysql -u $mysql_user -p${mysql_pass} -e '' > /dev/null 2>&1
test $? -gt 0 && echo "ERROR! Failed to connect to mysql" && exit 4
# bikin target kalo blum ada
test ! -d $target && mkdir -p $target
hari=`date +%A`
jam=`date +%H`
# get pwd
cwd=`pwd`
# looping
for section in `cat $inifile | grep '^\[' | grep -v main | sed 's/\[//' | sed 's/\]//'`; do
outdir=$target/$section/$hari/$jam
echo Backing up ${section} to $outdir...
# parse .ini
_parse_ini $inifile $section
# cek dulu
test ! -d $path && echo "Warning: $path not found. Backup process of $section skipped" && echo && continue
mysql -u $mysql_user -p${mysql_pass} -e '' $mysql_db > /dev/null 2>&1
test $? -gt 0 && echo "Warning: Database $mysql_db not found. Backup process of $section skipped" && echo && continue
test ! -d $outdir && mkdir -p $outdir
cd $path
tar -czpf $outdir/$section.tar.gz .
cd $cwd
mysqldump -Q -u $mysql_user -p${mysql_pass} $mysql_db | gzip > $outdir/${mysql_db}.sql.gz
ln -fs $outdir/$section.tar.gz $target/$section/latest.tar.gz
ln -fs $outdir/${mysql_db}.sql.gz $target/$section/latest.sql.gz
done