-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpakbak_script
executable file
·60 lines (49 loc) · 2.57 KB
/
pakbak_script
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
#!/bin/bash
# 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 <http://www.gnu.org/licenses/>.
# load configuration
# target_folder must contain the output directory for tar backups
# keep_days can be empty or contain the number of days to keep the backup
# keep_number can be empty or contain the number of backup to keep (the oldest backup will be removed when necessary)
source /etc/pakbak.conf
# abort when target_folder isn't a folder
[[ ! -d "$target_folder" ]] && echo "$target_folder isn't a folder.. abort" && exit 2
# abort when keep_days contains something other than numbers or is <= 0 and is not empty
[[ ( -n "$keep_days" ) && ( ! "$keep_days" =~ ^[0-9]+$ || ! "$keep_days" -gt 0 ) ]] && echo "keep_days=$keep_days isn't a valid number.. abort" && exit 3
# abort when $keep_number contains something other than numbers or is <= 0 and is not empty
[[ ( -n "$keep_number" ) && ( ! "$keep_number" =~ ^[0-9]+$ || ! "$keep_number" -gt 0 ) ]] && echo "keep_number=$keep_number isn't a valid number.. abort" && exit 3
# wait for pacman to exit (/var/lib/pacman/db.lck)
lockfile="/var/lib/pacman/db.lck"
while [[ -f "$lockfile" ]]; do
# TODO: check if pacman is still running
sleep 1s;
done
# make the backup before cleaning up old ones in case the backup fails
tar -cJf "$target_folder/pakbak-$(date +%Y-%m-%d-%H%M%S).tar.xz" "/var/lib/pacman/local" || exit $?
# cleanup old files
if [ -n "$keep_days" ]; then
find -H "$target_folder" -name 'pakbak-*.tar.xz' -type f -mtime +$keep_days -exec rm -v {} +
fi;
# cleanup files if there is too many of them (more than $keep_number)
if [ -n "$keep_number" ]; then
# Increment keep_number for correct tail handling
let keep_number=$keep_number+1
FILES_TO_DELETE=$(find -H "$target_folder" -name 'pakbak-*.tar.xz' -type f -print0 | \
xargs -0 stat --format "%Y %n" | \
sort -rn | \
cut -d' ' -f2- | \
tail -n +$keep_number)
for FILE in ${FILES_TO_DELETE}; do
rm -- "${FILE}"
done
fi;