Guest User

Untitled

a guest
Oct 21st, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2.  
  3. require 'fileutils'
  4. require 'aws'
  5.  
  6. # Change these values according to your configuration
  7. gmail_account = 'foo@gmail.com' # Gmail gmail_account that should be synced
  8. s3_bucket = 'gmvault-backup' # S3 bucket that the backups should be stored in
  9. password = 'secret' # The password used to encrypt the files
  10.  
  11. # Configure AWS
  12. AWS.config \
  13. access_key_id: ENV['AWS_ACCESS_KEY_ID'],
  14. secret_access_key: ENV['AWS_SECRET_ACCESS_KEY']
  15.  
  16. # Load bucket
  17. s3_bucket = AWS::S3.new.buckets[s3_bucket]
  18.  
  19. # Helper method to execute commands
  20. def execute(command)
  21. system(command).tap do |result|
  22. puts %(Error running command "#{command}") unless result
  23. end
  24. end
  25.  
  26. # Save start time before running Gmvault so we know which files have changed
  27. start = Time.now
  28.  
  29. # Do a quick sync (only last two months) and redirect STDOUT to /dev/null
  30. command = "gmvault sync --type quick #{gmail_account} > /dev/null"
  31. # Quit if sync fails
  32. exit unless execute(command)
  33.  
  34. gmvault_folder = File.join(Dir.home, 'gmvault-db')
  35. db_folders = Dir[File.join(gmvault_folder, 'db', '*')]
  36.  
  37. # Create "backup" folder inside Gmvault folder which will store the backup files
  38. FileUtils.mkdir_p File.join(gmvault_folder, 'backup')
  39.  
  40. # Pick only folders that have been changed during sync
  41. db_folders_to_upload = db_folders.sort.select do |db_folder|
  42. File.mtime(db_folder) > start
  43. end
  44.  
  45. # Compress, encrypt and upload each folder
  46. db_folders_to_upload.each do |db_folder|
  47. backup_filename = [db_folder.split('/').last, 'tar.gz'].join('.')
  48. backup_file = File.join(gmvault_folder, 'backup', backup_filename)
  49. encrypted_backup_filename = [backup_filename, 'gpg'].join('.')
  50. encrypted_backup_file = [backup_file, 'gpg'].join('.')
  51.  
  52. commands = [
  53. # Compress db folder (e.g. ~/gmvault-db/db/2012-06) into single file (e.g. ~/gmvault-db/backup/2012-06.tar.gz)
  54. "tar cvzfP #{backup_file} #{db_folder} > /dev/null",
  55.  
  56. # Encrypt the created file with the password
  57. "echo '#{password}' | gpg --symmetric --batch --yes --passphrase-fd 0 --output #{encrypted_backup_file} #{backup_file}"
  58. ]
  59.  
  60. # Skip to next folder if any command fails
  61. next unless commands.all?(&method(:execute))
  62.  
  63. # Upload to S3
  64. s3_bucket.objects[encrypted_backup_filename].write(file: encrypted_backup_file)
  65. end
Add Comment
Please, Sign In to add comment