#!/bin/bash
# Формат даты
DATE="$(date +%Y-%m-%d)"
# Каталог для хранения бекапов
STORAGEDIR="/backup"
# Список сайтов для копирования
SITES='/home/users'
EXCLUDE1="/home/users/<user_to_exclude>"
EXCLUDE2="/home/users/<username>/<sitename>/<folder_to_exclude>"
#Cписок конфигурационных файлов и других служебных файлов(Nagios,Cacti,Munin)
CONFIGS='/etc /usr/local/nagios /usr/lib64/nagios/plugins /usr/share/cacti /var/lib/cacti /var/www/html'
# Журналируем ошибки и успешное выполнение бекапа в файл
LOGFILE="/var/log/backup.log"
# Как долго(кол-во дней) хранить бекапы
LIMITTIME="+14"
# guess binary names
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
NICE="$(which nice)"
IONICE="$(which ionice)"
GZIP="$(which gzip)"
TAR="$(which tar)"
FIND="$(which find)"
MKDIR="$(which mkdir)"
ECHO="$(which echo)"
RM="$(which rm)"
# Пользователь,пароль,хост для подключения
MUSER="root"
MPASS="123"
MHOST="localhost"
[ ! -d $STORAGEDIR/sites ] && $MKDIR -p $STORAGEDIR/sites
[ ! -d $STORAGEDIR/configs ] && $MKDIR -p $STORAGEDIR/configs
[ ! -d $STORAGEDIR/mysql ] && $MKDIR -p $STORAGEDIR/mysql
$NICE -n 19 $IONICE -c2 -n7 $TAR -czf $STORAGEDIR/sites/sites-${DATE}.tar.gz $SITES --exclude=$EXCLUDE1 --exclude=$EXCLUDE2
exitcode=$?
if [ "$exitcode" != "1" ] && [ "$exitcode" != "0" ];
then
$ECHO "Backup sites is failed - $DATE" | tee -a $LOGFILE
fi
$NICE -n 19 $IONICE -c2 -n7 $TAR -czf $STORAGEDIR/configs/configs-${DATE}.tar.gz $CONFIGS
exitcode=$?
if [ "$exitcode" != "1" ] && [ "$exitcode" != "0" ];
then
$ECHO "Backup configs is failed - $DATE" | tee -a $LOGFILE
fi
DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases' | egrep -v '(information_schema|performance_schema)')"
for db in $DBS
do
FILE=$STORAGEDIR/mysql/$db-${DATE}.sql.gz
$MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS -EKR --single-transaction $db | $GZIP -c > $FILE
if [ ${PIPESTATUS[0]} != "0" ];
then
$ECHO "Backup database is failed $db - $DATE" | tee -a $LOGFILE
fi
done
$NICE -n 19 $IONICE -c2 -n7 $TAR -cf $STORAGEDIR/backup-all-${DATE}.tar $STORAGEDIR/sites/*.tar.gz $STORAGEDIR/configs/*.tar.gz $STORAGEDIR/mysql/*.sql.gz
exitcode=$?
if [ "$exitcode" != "1" ] && [ "$exitcode" != "0" ];
then
$ECHO "Tar sites,config,databases is failed - $DATE" | tee -a $LOGFILE
else
$RM -rf $STORAGEDIR/sites/* $STORAGEDIR/configs/* $STORAGEDIR/mysql/*
$ECHO "Backup sites,configs,databases is done! Backup up to $DATE " | tee -a $LOGFILE
fi
# Удаляем бекапы старше 14 дней
$FIND $STORAGEDIR -maxdepth 1 -type f -name '*.tar' -mtime $LIMITTIME -exec $RM -rf {} \;