namespace :idobata do

task :setup do
  Idobata.hook_url = fetch(:idobata_hook_url)
end

namespace :notify do
  task :starting do
    source = "#{deployer} started deployment"
    send_notification(source: source, type: :info)
  end

  task :finished do
    branch_url   = "#{fetch(:repository_url)}/tree/#{fetch(:branch)}"
    revision_url = "#{fetch(:repository_url)}/commit/#{fetch(:current_revision)}"

    source  = "Branch <a href='#{branch_url}'>#{fetch(:branch)}</a> "
    source += "(at <a href='#{revision_url}'>#{fetch(:current_revision)}</a>) "
    source += "was deployed by #{deployer}"
    send_notification(source: source, type: :success)
  end

  task :failed do
    source = "Deployment by #{deployer} has failed"
    send_notification(source: source, type: :danger)
  end
end

end

namespace :deploy do

before 'starting', 'idobata:setup'

after 'starting', 'idobata:notify:starting'
after 'finished', 'idobata:notify:finished'
after 'failed',   'idobata:notify:failed'

end

def deployer

ENV['DEPLOYER'] || `git config user.name`.chomp

end

def send_notification(source:, type:)

label =
  (['Deploy', fetch(:stage)] + Array(fetch(:idobata_additional_label))).collect do |text|
    { type: type, text: text }
  end
Idobata::Message.create(format: :html, source: source, label: label)

rescue Faraday::ClientError end