Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- require 'fileutils'
- require 'aws'
- # Change these values according to your configuration
- gmail_account = 'foo@gmail.com' # Gmail gmail_account that should be synced
- s3_bucket = 'gmvault-backup' # S3 bucket that the backups should be stored in
- password = 'secret' # The password used to encrypt the files
- # Configure AWS
- AWS.config \
- access_key_id: ENV['AWS_ACCESS_KEY_ID'],
- secret_access_key: ENV['AWS_SECRET_ACCESS_KEY']
- # Load bucket
- s3_bucket = AWS::S3.new.buckets[s3_bucket]
- # Helper method to execute commands
- def execute(command)
- system(command).tap do |result|
- puts %(Error running command "#{command}") unless result
- end
- end
- # Save start time before running Gmvault so we know which files have changed
- start = Time.now
- # Do a quick sync (only last two months) and redirect STDOUT to /dev/null
- command = "gmvault sync --type quick #{gmail_account} > /dev/null"
- # Quit if sync fails
- exit unless execute(command)
- gmvault_folder = File.join(Dir.home, 'gmvault-db')
- db_folders = Dir[File.join(gmvault_folder, 'db', '*')]
- # Create "backup" folder inside Gmvault folder which will store the backup files
- FileUtils.mkdir_p File.join(gmvault_folder, 'backup')
- # Pick only folders that have been changed during sync
- db_folders_to_upload = db_folders.sort.select do |db_folder|
- File.mtime(db_folder) > start
- end
- # Compress, encrypt and upload each folder
- db_folders_to_upload.each do |db_folder|
- backup_filename = [db_folder.split('/').last, 'tar.gz'].join('.')
- backup_file = File.join(gmvault_folder, 'backup', backup_filename)
- encrypted_backup_filename = [backup_filename, 'gpg'].join('.')
- encrypted_backup_file = [backup_file, 'gpg'].join('.')
- commands = [
- # Compress db folder (e.g. ~/gmvault-db/db/2012-06) into single file (e.g. ~/gmvault-db/backup/2012-06.tar.gz)
- "tar cvzfP #{backup_file} #{db_folder} > /dev/null",
- # Encrypt the created file with the password
- "echo '#{password}' | gpg --symmetric --batch --yes --passphrase-fd 0 --output #{encrypted_backup_file} #{backup_file}"
- ]
- # Skip to next folder if any command fails
- next unless commands.all?(&method(:execute))
- # Upload to S3
- s3_bucket.objects[encrypted_backup_filename].write(file: encrypted_backup_file)
- end
Add Comment
Please, Sign In to add comment