require File.join(File.dirname(__FILE__), '..', 'vendor', 'backpack.rb')

RAILS_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', '..')) unless defined?(RAILS_ROOT)

after 'deploy', 'capback:post'
namespace :capback do
  task :post do
    # This method is pretty ugly. The regex doesn't actually work every time.
    # TODO Improve grepping of revision name.
    def git_revision
      revision = `cd #{RAILS_ROOT} && git show | grep commit` 
      revision.gsub!(/^commit\s*/, '')
      revision.gsub!(/\n|\|/, '')
      revision
    end

    # Grab the log entry for this revision.
    # TODO Improve grepping of log entry
    def git_log_entry
      `cd #{RAILS_ROOT} && git show --no-color`.match(/\n\n\s{4,}([^(\n\n)]*)/)[1] rescue ''
    end

    # Actually posts to backpack.
    # TODO It's not necessary to pass most of the arguments here, since they
    #      should already be available in context.
    def post_to_backpack(username, token, page_id, branch, rails_env)
      logger.info "connecting to backpack"
      @b = Backpack.new(username, token)
      @b.page_id = page_id
      logger.info "posting to backpack"
      @b.create_note \
        "#{`date`}",
        <<-STR
        |Application|#{application}|
        |Environment|@#{rails_env.upcase}@|
        |Branch|@#{branch}@|
        |Revision|@#{git_revision}@|
        |Log Entry|@#{git_log_entry}@|
        |Deployer|#{`whoami`}|
        STR
      logger.info "done."
    end
    
    post_to_backpack \
      backpack_username,
      backpack_token,
      backpack_page_id,
      branch,
      rails_env
  end
end