Last active
April 16, 2018 14:17
-
-
Save alekratz/b6c25a872d63096d126f9fc795ea7a41 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -e | |
show_usage() { | |
echo "usage: $0 [-bd]" | |
echo | |
echo "-b run backups only" | |
echo "-d dry run (don't create or delete any files)" | |
} | |
dry_run_command() { | |
if [[ "$dry_run" == "0" ]]; then | |
"$@" | |
else | |
echo "DRY RUN: skipping execution of $1" | |
fi | |
} | |
backup_only=0 | |
dry_run=0 | |
while getopts ":bd" opt; do | |
case "$opt" in | |
'b') | |
backup_only=1 | |
;; | |
'd') | |
dry_run=1 | |
;; | |
\?) | |
show_usage | |
exit | |
;; | |
esac | |
done | |
umask 0002 | |
max_backups=20 | |
backup="/var/backups/reports" | |
prod="/var/www/sites/report" | |
beta="/var/www/sites/beta/Reports" | |
backup_file="$(date '+%Y%m%d%H%M%S')-reports.tgz" | |
backup_path="$backup/$backup_file" | |
echo "Creating backup $backup_file" | |
dry_run_command tar cfz "$backup_path" --strip-components=3 "$prod" | |
# Prune latest backup | |
cd "$backup" | |
dirlen=$(find . -name "*-reports.tgz" -type f | wc -l) | |
while (( "$dirlen" > "$max_backups" )); do | |
which=$(find . -name "*-reports.tgz" -type f | cut -d '-' -f 1 | sort -n | head -n 1) | |
remove="$backup/$which-reports.tgz" | |
dry_run_command rm -v "$remove" | |
if [[ "$dry_run" == "1" ]]; then | |
break | |
fi | |
dirlen=$(find . -name "*-reports.tgz" -type f | wc -l) | |
done | |
if [[ "$backup_only" == "0" ]]; then | |
echo "Removing old production" | |
dry_run_command rm -r "$prod"/* | |
echo "Copying current beta into production" | |
dry_run_command cp -r "$beta"/* "$prod"/ | |
else | |
echo "Running backup only - skipping copy to production" | |
fi | |
echo "Done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment