## # Usage: # ./bin/cap production mongo:pull # COLLECTION=agents ./bin/cap production mongo:pull # COLLECTION=agents IDS=1,2,3 ./bin/cap production mongo:pull # ./bin/cap production mongo:sync_prod_to_staging

namespace :mongo do

set :remote_dump_base, '/tmp/dumps'
set :local_dump_base, '/tmp/dumps'
set :collection, ENV['COLLECTION'] || 'full'
set :collection_ids, ENV['IDS']

task :sync_prod_to_staging do
  set :from_db, fetch(:production_db)

  on roles(:db) do
    ms_remote = MongoSync.new(self)
    ms_remote.hipchat_notify! 'Engineering', 'capistrano', 'Started syncing prod to staging...', color: 'yellow'
    ms_remote.remote_setup!
    ms_remote.remote_cleanup!

    remote_dump_dir = ms_remote.last_remote_dump
    remote_dump_dir ||= ms_remote.remote_mongodump!

    ms_remote.staging_mongorestore! remote_dump_dir
    ms_remote.hipchat_notify! 'Engineering', 'capistrano', 'Finished syncing prod to staging...', color: 'green'
  end
end

task :pull do
  set :from_db, :production == fetch(:stage) ? fetch(:production_db) : fetch(:staging_db)

  run_locally do
    ms_local = MongoSync.new(self)
    ms_local.local_setup!
    ms_local.local_cleanup!

    # variable scope
    remote_tgz = nil
    local_tgz = nil

    if local_tgz = ms_local.last_local_dump
      # use local tgz
      ms_local.local_unarchive! local_tgz

      local_dump_dir = File.join fetch(:local_dump_base), File.basename(local_tgz, '.tgz')
      ms_local.local_mongorestore!(local_dump_dir)
    else
      # get dump from remote
      on roles(:db) do
        ms_remote = MongoSync.new(self)
        ms_remote.remote_setup!
        ms_remote.remote_cleanup!

        # find & choose tarfile or dump & archive
        remote_tgz = ms_remote.last_remote_dump_tgz
        unless remote_tgz
          dump_dir = ms_remote.remote_mongodump!
          remote_tgz = ms_remote.remote_archive! dump_dir
        end

        # download!
        local_tgz = File.join fetch(:local_dump_base), File.basename(remote_tgz)
        download! remote_tgz, local_tgz, method: :scp
      end

      # unarchive!
      ms_local.local_unarchive!(local_tgz)

      # restore!
      local_dump_dir = File.join fetch(:local_dump_base), File.basename(remote_tgz, '.tgz')
      ms_local.local_mongorestore!(local_dump_dir)
    end
  end
end

end