namespace :git_sync do

namespace :push do
  desc 'Push public/system files to staging'
  task :staging => :environment do
    do_rsync_push('staging')
  end
  desc 'Push public/system files to production'
  task :production => :environment do
    do_rsync_push('production')
  end
end

namespace :pull do
  desc 'Pull public/system files from staging'
  task :staging => :environment do
    do_rsync_pull('staging')
  end
  desc 'Pull public/system files from production'
  task :production => :environment do
    do_rsync_pull('production')
  end
end

private

def do_rsync_push(remote)
  remote_url = extract_git_remote(remote)
  if remote_url
    command = "rsync -ruzv public/system #{remote_url}/public/"
    logger.info "Running command: #{command}"
    IO.popen(command).each{ |output| logger.info(output.chomp) }
  end
end

def do_rsync_pull(remote)
  remote_url = extract_git_remote(remote)
  if remote_url
    command = "rsync -ruzv #{remote_url}/public/system public/"
    logger.info "Running command: #{command}"
    IO.popen(command).each{ |output| logger.info(output.chomp) }
  end
end

def extract_git_remote(remote)
  git_result = `git remote show #{remote}`
  if git_result
    match_data = git_result.match(/Fetch URL: (.+)\n/)
    if match_data.nil? || match_data.length < 1
      logger.fatal "Failed to reason out the git remote url. Git returned:"
      logger.fatal git_result
      return false
    else
      remote_url = match_data[1]
      return remote_url
    end
  end
end

def logger
  @_logger = Logger.new(STDOUT) if @_logger.nil?
  return @_logger
end

end