@@ -24,8 +24,53 @@ if [ -e $backup_file ]; then rm $backup_file; fi
2424umask 177
2525# Dump database into SQL file
2626pg_dump -h $host -p 5432 -U $user -w $db_name | gzip > $backup_file
27- # Delete files older than 30 days
28- find $backup_path /* .sql.gz -mtime +30 -exec rm {} \;
27+ # Remove all files not within 7 days, most recent per month for 6 months, or most recent of the year
28+ echo " removing:"
29+ ls " $backup_path " /moqui-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9].sql.gz | awk -v now_epoch=" $( date +%s) " '
30+ {
31+ date_string = substr($0, index($0,"-")+1, 8)
32+ command = "date -d \"" date_string "\" +%s"
33+ command | getline file_epoch
34+ close(command)
35+
36+ files[NR] = $0
37+ file_epoch_by_name[$0] = file_epoch
38+
39+ year_month = substr(date_string,1,6)
40+ year_only = substr(date_string,1,4)
41+
42+ age_in_months = int((now_epoch - file_epoch) / 2592000)
43+
44+ if (age_in_months < 6 &&
45+ (!(year_month in newest_month_epoch) ||
46+ file_epoch > newest_month_epoch[year_month])) {
47+ newest_month_epoch[year_month] = file_epoch
48+ newest_month_file[year_month] = $0
49+ }
50+
51+ if (!(year_only in newest_year_epoch) ||
52+ file_epoch > newest_year_epoch[year_only]) {
53+ newest_year_epoch[year_only] = file_epoch
54+ newest_year_file[year_only] = $0
55+ }
56+ }
57+ END {
58+ for (i in files) {
59+ file_name = files[i]
60+ file_epoch = file_epoch_by_name[file_name]
61+
62+ date_string = substr(file_name, index(file_name,"-")+1, 8)
63+ year_month = substr(date_string,1,6)
64+ year_only = substr(date_string,1,4)
65+
66+ if (now_epoch - file_epoch <= 7*86400) continue
67+ if (file_name == newest_month_file[year_month]) continue
68+ if (file_name == newest_year_file[year_only]) continue
69+
70+ printf "%s\0", file_name
71+ }
72+ }' |
73+ xargs -0 --no-run-if-empty rm -v
2974
3075# update cloned test instance database using backup file from production/main database
3176# docker stop moqui-test
@@ -35,4 +80,3 @@ find $backup_path/*.sql.gz -mtime +30 -exec rm {} \;
3580# docker start moqui-test
3681
3782# example for crontab (safe edit using: 'crontab -e'), each day at midnight: 00 00 * * * /opt/moqui/postgres_backup.sh
38-
0 commit comments