getRemoteBackup.sh 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/bin/bash
  2. #Read the backup folders from the config script outside the git repo
  3. . $1
  4. #Example script
  5. #declare -A backup_folders
  6. #backup_folders["/opt/SourceFolderA"]="opt/backup/folderA"
  7. #backup_folders["/opt/SourceFolderB"]="opt/backup/folderB"
  8. #Configuration
  9. logPath=/home/sebastian/ARCHIVE/sebastian/3000_BACKUP/
  10. logFileName="$(date +'%Y-%m-%d_%H-%M')_backupjobs.log"
  11. tmpLogFilePath=/tmp/tmp_backup.log
  12. retryAttempts=2
  13. #Delete logs older than rotationDays
  14. rotationDays=14
  15. #Variables
  16. globalErrors=0
  17. logFilePath="${logPath}${logFileName}"
  18. touch $tmpLogFilePath
  19. touch $logFilePath
  20. echo $logFilePath
  21. #Terminate if the last backup has not finished yet
  22. if pidof -o %PPID -x "$0" > /dev/null; then
  23. echo "Backup job already running. Exiting..."
  24. exit
  25. fi
  26. echo "Starting backup job(s)" | tee $tmpLogFilePath
  27. for sourceFolder in "${!backup_folders[@]}"
  28. do
  29. mkdir -p ${backup_folders[$sourceFolder]}
  30. while [ "$retryAttempts" -ge "0" ]
  31. do
  32. echo "Starting Job" | tee -a $tmpLogFilePath
  33. echo "SRC: ${sourceFolder}" | tee -a $tmpLogFilePath
  34. echo "DEST: ${backup_folders[$sourceFolder]}" | tee -a $tmpLogFilePath
  35. date | tee -a $tmpLogFilePath
  36. #SSH Host settings need to be set in the ssh client config!
  37. rsync --delete --out-format="%t %f %''b" -avz $sourceFolder ${backup_folders[$sourceFolder]} | tee -a $tmpLogFilePath 2>&1
  38. rsyncExitCode=$?
  39. echo "Ending backup job" | tee -a $tmpLogFilePath
  40. date | tee -a $tmpLogFilePath
  41. echo "" | tee -a $tmpLogFilePath
  42. if [ $rsyncExitCode -eq 0 ]; then
  43. break
  44. else
  45. echo "Error: rsync exited with code $rsyncExitCode. Retrying..." | tee -a $tmpLogFilePath
  46. retryAttempts=$((retryAttempts-1))
  47. globalErrors=$((globalErrors+1))
  48. fi
  49. done
  50. done
  51. #copy over and delete older logs
  52. cat $tmpLogFilePath > $logFilePath
  53. find $logPath -type f -mtime +$rotationDays -name '*.log' -execdir rm -- '{}' \;
  54. #Mail Notifications
  55. if [ $globalErrors -eq 0 ]; then
  56. #send mail for success
  57. echo -e "To:mail@sebastianvendt.de\nFrom:Sebastian@manaslu.home\nSubject:Backup SUCCESSFUL on $(date +'%c')\n\n$(cat $tmpLogFilePath)" | sendmail mail@sebastianvendt.de
  58. else
  59. #send mail for failure
  60. echo -e "To:mail@sebastianvendt.de\nFrom:Sebastian@manaslu.home\nSubject:Backup FAILED on $(date +'%c')\n\n$(cat $tmpLogFilePath)" | sendmail mail@sebastianvendt.de
  61. fi
  62. #delete tmp file
  63. rm $tmpLogFilePath