Hugo/scripts/nextcloud/backup-database.sh

82 lines
2.5 KiB
Bash
Raw Normal View History

2023-10-07 11:04:32 +02:00
#!/bin/bash
# Backup Nextcloud database in a Kubernetes environment.
# Usage: backup-database <destination>
usage() {
>&2 printf "Usage: %s <destination>\n" "${0}"
exit "${1:-1}"
}
# Get options
while getopts ":e:" option; do
case "${option}" in
e)
if ! [ -f "${OPTARG}" ]; then
>&2 printf "Error: Specified environment file does not exist: '%s'.\n" "${OPTARG}"
elif ! [ -r "${OPTARG}" ]; then
>&2 printf "Error: Specified environment file is not readable: '%s'.\n" "${OPTARG}"
fi
env_file="${OPTARG}"
;;
*)
>&2 printf "Error: Invalid option: '%s'.\n" "${option}"
usage
;;
esac
done
2023-10-10 22:34:14 +02:00
shift $(( OPTIND - 1 ))
2023-10-07 11:04:32 +02:00
# Check arguments.
if [ $# -ne 1 ]; then
>&2 printf "Error: You need to specify a destination.\n"
usage
elif ! [ -d "${1}" ]; then
>&2 printf "Error: Specified destination does not exist or is not readable : '%s'.\n" "${1}"
usage
else
destination="${1}"
fi
namespace="ix-nextcloud-2"
2023-10-07 11:04:32 +02:00
# Filename for database backup
database_backupfile="nextcloud-sqlbkp_$(date +'%Y%m%d').bak"
# Retrieve container names
base_container="$( k3s kubectl get pods --namespace "${namespace}" | cut -f1 -d' ' | grep -E 'nextcloud-2-[0-9a-z]{10}-[0-9a-z]{5}' )"
database_container="$( k3s kubectl get pods --namespace "${namespace}" | cut -f1 -d' ' | grep 'cnpg-main' )"
2023-10-07 11:04:32 +02:00
if ! [[ -n "${base_container}" && -n "${database_container}" ]]; then
>&2 printf "Error: Not all containers could be found.\n"
exit 2
fi
# Abort entire script if any command fails
set -e
# Turn on maintenance mode
k3s kubectl exec "${base_container}" --namespace "${namespace}" -- php occ maintenance:mode --on
2023-10-07 11:04:32 +02:00
# Database backup
echo 'Backing up database'
host_database_backupfile="${destination}/${database_backupfile}"
k3s kubectl exec "${database_container}" --namespace "${namespace}" -- env $(cat "${env_file:=.env}" | xargs) pg_dump 'nextcloud' -cwv -h 'localhost' -U 'nextcloud' > "${host_database_backupfile}"
2023-10-07 11:04:32 +02:00
# Files backup
for file in 'config' 'themes'; do
2023-10-10 22:34:14 +02:00
printf "Copying %s\n" "${file}"
k3s kubectl --namespace "${namespace}" cp "${base_container}":"/var/www/html/${file}" "${destination}"
2023-10-07 11:04:32 +02:00
done
# Turn off maintenance mode
k3s kubectl exec "${base_container}" --namespace "${namespace}" -- php occ maintenance:mode --off
2023-10-07 11:04:32 +02:00
# Backup cleanup
# Only keep 30 days of backups
2023-10-10 22:34:14 +02:00
printf "Clean up old database backups.\n"
2023-10-07 11:04:32 +02:00
find "${destination}" -name '*sqlbkp*' -type f -mtime +30 -print -delete
2023-10-10 22:34:14 +02:00
printf "Done\n"