2024-07-11 21:18:02 +05:00
|
|
|
#!/bin/bash
|
|
|
|
|
|
|
|
if [ "$(id -u)" != "0" ]; then
|
2024-08-08 05:50:15 +05:00
|
|
|
echo -e "\033[31mThis script requires superuser rights\033[0m"
|
2024-07-11 21:18:02 +05:00
|
|
|
exit 0
|
|
|
|
fi
|
|
|
|
|
|
|
|
if [ -z "$1" ] || [ -z "$2" ]; then
|
2024-08-08 05:50:15 +05:00
|
|
|
echo "Please provide both the POSTGRES_DB and POSTGRES_USER as arguments"
|
2024-07-11 21:18:02 +05:00
|
|
|
exit 1
|
|
|
|
fi
|
|
|
|
|
2024-08-14 10:49:57 +05:00
|
|
|
trap 'echo -e "\033[31mpostgres.sh: Something went wrong\033[0m"; exit 1' ERR
|
2024-07-11 21:18:02 +05:00
|
|
|
set -e
|
|
|
|
|
|
|
|
export DEBIAN_FRONTEND=noninteractive
|
|
|
|
|
2024-08-08 05:50:15 +05:00
|
|
|
PGDB="$1"
|
|
|
|
PGUSER="$2"
|
2024-07-11 21:18:02 +05:00
|
|
|
|
|
|
|
CURRENT_MONTH=$(date +%Y-%m)
|
|
|
|
CURRENT_DATE=$(date +%Y-%m-%d)
|
2024-08-08 05:50:15 +05:00
|
|
|
CURRENT_DATETIME=$(date +%d-%m-%Y_%H%M%S)
|
|
|
|
BACKUPS_PATH=/backups/postgres
|
2024-07-11 21:18:02 +05:00
|
|
|
DOCKER_SERVICE_NAME=postgres
|
|
|
|
|
2024-08-08 05:50:15 +05:00
|
|
|
BACKUP_FOLDER=$BACKUPS_PATH/$PGDB
|
2024-08-14 10:49:57 +05:00
|
|
|
|
|
|
|
echo 'check BACKUP_FOLDER...'
|
|
|
|
mkdir -p "$BACKUP_FOLDER"
|
|
|
|
|
2024-07-11 21:18:02 +05:00
|
|
|
|
|
|
|
echo 'Creating PostgreSQL backups...'
|
|
|
|
cd "$BACKUP_FOLDER"
|
2024-08-08 05:50:15 +05:00
|
|
|
if [ -f 'dump_'"$PGDB"'.sql' ]; then
|
|
|
|
rm 'dump_'"$PGDB"'.sql'
|
2024-07-11 21:18:02 +05:00
|
|
|
fi
|
2024-08-14 10:49:57 +05:00
|
|
|
DB_BACKUP_FILENAME=$PGDB'_'$CURRENT_DATETIME'.tar.gz'
|
2024-07-11 21:18:02 +05:00
|
|
|
|
2024-08-14 10:49:57 +05:00
|
|
|
echo 'Exec pg_dump...'
|
2024-08-08 05:50:15 +05:00
|
|
|
docker exec -t postgres pg_dump -U $PGUSER $PGDB > 'dump_'"$PGDB"'.sql'
|
2024-07-11 21:18:02 +05:00
|
|
|
|
2024-08-14 10:49:57 +05:00
|
|
|
echo 'Pack to tar.gz...'
|
|
|
|
tar -cf - 'dump_'"$PGDB"'.sql' | gzip -9 > "$DB_BACKUP_FILENAME"
|
2024-08-08 05:50:15 +05:00
|
|
|
rm 'dump_'"$PGDB"'.sql'
|
2024-07-11 21:18:02 +05:00
|
|
|
|
|
|
|
cd "$BACKUP_FOLDER"
|
2024-08-14 10:49:57 +05:00
|
|
|
|
|
|
|
echo 'Write md5 sum...'
|
2024-07-11 21:18:02 +05:00
|
|
|
md5sum * > MD5SUMS
|
|
|
|
|
2024-08-14 10:49:57 +05:00
|
|
|
trap - ERR
|
2024-08-08 05:50:15 +05:00
|
|
|
echo 'The backup of the '"$PGDB"' database was completed successfully'
|