require 'yaml'

Capistrano::Configuration.instance(:must_exist).load do
  namespace :notify do
    begin
      require 'tinder'
    rescue LoadError
      def notify(action)
        puts "[!] Please `gem install tinder' to post deployment messages to Campfire."
      end
    else
      def notify(action)
        fingercap = nil
        begin
          fingercap = YAML.load_file(File.expand_path('~/.fingercap.yml'))
        rescue Errno::ENOENT
          puts "[!] Fingercap can't find it's configuration file"
          puts File.read(File.expand_path('../../../../examples/fingercap.yml', __FILE__))
          exit -1
        end
        if config = fingercap['campfire']
          campfire = Tinder::Campfire.new(config['account'], :ssl => (config['use_ssl']||false))
          if campfire.login(config['username'], config['password'])
            if room = campfire.find_room_by_name(config['room'])
              room.speak "#{ENV['USER'].titlecase} just #{action} #{application}: #{repository}" 
            end
          end
        else
          puts "[!] Fingercap can't post deployment messages to Campfire because there are no credentials in the configuration file (~/.fingercap.yml)"
        end
      end
    end
    
    desc "Posts a `deployed' message to Campfire"
    task :deploy do
      notify "deployed"
    end
    
    desc "Posts a `deployed and migrated' message to Campfire"
    task :migrations do
      notify "deployed and migrated"
    end
  end
end