This repository has been archived by the owner on Feb 3, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbackup.sh
73 lines (60 loc) · 2.06 KB
/
backup.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env bash
# Define color escape codes
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Define the root folder containing your subfolders with docker-compose.yml files
ROOT_FOLDER="."
BACKUP_ROOT="./backup"
# Create the backup root directory if it doesn't exist
mkdir -p "$BACKUP_ROOT"
# Get the current day of the week (1 for Monday, 7 for Sunday)
DAY_OF_WEEK=$(date +%u)
# Get the current date and time for the backup file naming
TIMESTAMP=$(date +%F-%H-%M)
# Function to backup a folder and handle Docker containers
backup_folder() {
local dir="$1"
local dirname=$(basename "$dir")
local was_running=false
local container_status="stopped_color"
if [ -f "$dir/docker-compose.yml" ]; then
# Check if any container is running in this folder
if docker compose -f "$dir/docker-compose.yml" ps | grep -q 'Up'; then
was_running=true
container_status="${GREEN}running${NC}"
echo -e "Stopping containers in ${YELLOW}$dir${NC}"
docker compose -f "$dir/docker-compose.yml" down
else
container_status="${RED}stopped${NC}"
fi
echo -e "Performing backup of $container_status container: ${YELLOW}$dirname${NC}"
# Create the backup directory structure
backup_dir="$BACKUP_ROOT/$DAY_OF_WEEK-$(date +%A)/$dirname"
mkdir -p "$backup_dir"
backup_file="$backup_dir/$TIMESTAMP.tgz"
# Create the tar.gz backup
echo "Backing up $dir to $backup_file"
tar --create --gzip --preserve-permissions --file="$backup_file" -C "$ROOT_FOLDER" "$dirname"
# Restart the containers if they were running before
if [ "$was_running" = true ]; then
echo -e "Starting containers in ${YELLOW}$dir${NC}"
docker compose -f "$dir/docker-compose.yml" up -d
fi
# Print an empty line before the footer line
echo ""
# Print the footer line
echo "########################################"
fi
}
# Main script execution
if [ $# -eq 0 ]; then
for dir in "$ROOT_FOLDER"/*/; do
if [ -d "$dir" ]; then
backup_folder "$dir"
fi
done
else
backup_folder "$1"
fi