require 'httparty'

before 'deploy:starting', 'rocket_chat_notify:starting' before 'deploy:failed', 'rocket_chat_notify:failed' before 'deploy:finished', 'rocket_chat_notify:finished'

namespace :rocket_chat_notify do

desc 'Notify rocket-chat on start of deployment'
task :starting do |task|
  on roles(:all) do |host|
    notify(:starting)
  end
end
task :finished do |task|
  on roles(:all) do |host|
    notify(:finished)
  end
end
task :failed do |task|
  on roles(:all) do |host|
    notify(:failed)
  end
end

end

def get_config_vars()

return {
  rocket_chat_url: fetch(:rocket_chat_webhook_url),
  rocket_chat_channel: fetch(:rocket_chat_channel),
  application: fetch(:application),
  branch: fetch(:branch),
  repo_url: fetch(:repo_url),
  stage: fetch(:stage),
  deploy_to: fetch(:deploy_to),
  rails_env: fetch(:rails_env),
  scm: fetch(:scm),
  log_level: fetch(:log_level),
  local_user: @task.local_user,
  server: {
    name: @host.hostname,
    user: @host.user
  }
 }

end

def notify(event_hook)

config = get_config_vars

raise "\n\nERROR::ROCKET-CHAT-TASK: config option 'rocket_chat_webhook_url' is not set\n\n" unless config[:rocket_chat_url]

notification_text = "#{event_hook} deployment to '#{config[:server][:name]}' on branch '#{config[:branch]}' to stage '#{config[:stage]}'"

if dry_run?
  puts "[Rocket Chat] #{event_hook}"
  puts "[Rocket Chat] #{notification_text}"
  return
end

request_body = {
  event: {
    hook: event_hook,
    text: notification_text
  },
  attributes: config
}

begin
  puts "[Rocket Chat] #{event_hook}"
  HTTParty.post("#{config[:rocket_chat_url]}", body: request_body, timeout: 10).body
rescue => e
  puts "[Rocket Chat] Error notifying Rocket chat!"
  puts "[Rocket Chat] Error: #{e.inspect}"
end

end