91 lines
2.6 KiB
Bash
Executable File
91 lines
2.6 KiB
Bash
Executable File
#!/bin/bash
|
|
|
|
# Backup a sql database, args come from the environment
|
|
# $1, if it exists, contains a list of declarations
|
|
|
|
# Copyright (C) 2019 Carlos Galindo
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify
|
|
# it under the terms of the GNU General Public License as published by
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU General Public License
|
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
if [ -e "$1" ]; then
|
|
source $1
|
|
fi
|
|
|
|
if [ -z "${outDir}" -o -z "${dbName}" -o -z "${dbPassword}" -o -z "${dbUser}" \
|
|
-o -z "${maxBackups}" -o -z "${service}" ]
|
|
then
|
|
echo "ERROR: Missing data, you need to declare the following:"
|
|
echo "\toutDir: the directory where the backup will be saved"
|
|
echo "\tdbName, dbUser, dbPassword: database settings"
|
|
echo "\tservice: the service to be stopped (webserver)"
|
|
echo "\tmaxBackups: the number of backups to keep (0 = infinite)"
|
|
exit 1
|
|
fi
|
|
|
|
if [ "$(id -u)" != "0" ]
|
|
then
|
|
echo "ERROR: this script has to be run as root!"
|
|
exit 1
|
|
fi
|
|
|
|
dateDir="${outDir}/$(date +"%Y%m%d_%H%M%S")"
|
|
|
|
if [ ! -d "${dateDir}" ]
|
|
then
|
|
mkdir -p "${dateDir}"
|
|
else
|
|
echo "ERROR: the backup directory ${dateDir} already exists!"
|
|
exit 1
|
|
fi
|
|
|
|
echo "Begin backup for sql db ${dbName}, at ${dateDir}"
|
|
|
|
echo -n "Stopping service ${service}..."
|
|
systemctl stop "${service}"
|
|
echo " OK"
|
|
|
|
trap 'echo -n "Starting service ${service}..."; systemctl start "${service}"; echo " OK"; exit 2' 1 2 3 9 15
|
|
|
|
echo -n "Backing up ${dbName} database..."
|
|
mysqldump --single-transaction -h localhost -u "${dbUser}" -p"${dbPassword}" "${dbName}" > "${dateDir}/${dbName}.sql"
|
|
echo " OK"
|
|
|
|
echo -n "Starting service ${service}..."
|
|
systemctl start "${service}"
|
|
echo " OK"
|
|
|
|
echo -n "Compressing backed up database..."
|
|
pushd "${dateDir}" > /dev/null
|
|
xz -9 "${dbName}.sql"
|
|
sha256sum * > sha256sums
|
|
popd > /dev/null
|
|
echo " OK"
|
|
|
|
if (( ${maxBackups} != 0 ))
|
|
then
|
|
nrOfBackups=$(ls -l ${outDir} | grep -c ^d)
|
|
|
|
if (( ${nrOfBackups} > ${maxBackups} ))
|
|
then
|
|
echo "Removing old backups..."
|
|
ls -t ${outDir} | tail -$(( nrOfBackups - maxBackups )) | while read dirToRemove; do
|
|
echo -n "Deleting ${dirToRemove}..."
|
|
rm -r ${outDir}/${dirToRemove}
|
|
echo " OK"
|
|
done
|
|
fi
|
|
fi
|
|
|
|
echo "End of SQL backup for ${dbName}, at ${dateDir}"
|