run_backup.sh 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/bin/bash
  2. # Load environment variables from .env file
  3. source .env
  4. # Export Borg passphrase
  5. export BORG_PASSPHRASE=$PASSPHRASE
  6. export BORG_RSH="ssh -i $SSH_KEY -p $SSH_PORT"
  7. # Build the list of existing directories
  8. EXISTING_DIRECTORIES=$(for DIR in $SOURCE_DIRECTORIES; do
  9. if [ -d "$DIR" ]; then
  10. echo "$DIR"
  11. else
  12. echo "Directory does not exist: $DIR"
  13. fi
  14. done)
  15. # If we have valid directories, run the backup
  16. if [ -n "$EXISTING_DIRECTORIES" ]; then
  17. echo "Backing up directories: $EXISTING_DIRECTORIES"
  18. sudo -E borg create --stats "$SERVER_USER@$SERVER_IP:$REPOSITORY::{hostname}-{now}" $EXISTING_DIRECTORIES
  19. if [ $? -ne 0 ]; then
  20. echo "Borg backup failed."
  21. exit 1
  22. fi
  23. else
  24. echo "No valid directories to back up."
  25. exit 1
  26. fi
  27. # Prune old backups using a custom SSH port
  28. sudo -E borg prune --glob-archives '{hostname}-*' --keep-daily=7 --keep-weekly=4 --keep-monthly=6 --keep-yearly=10 "$SERVER_USER@$SERVER_IP:$REPOSITORY"
  29. if [ $? -ne 0 ]; then
  30. echo "Borg prune failed."
  31. exit 1
  32. fi
  33. sudo -E borg compact
  34. if [ $? -ne 0 ]; then
  35. echo "Borg compact failed."
  36. exit 1
  37. fi