namespace :ci do
  desc 'Delivers stories to tracker'
  task :deliver do
    require 'pivotal-tracker'
    TRACKER_TOKEN = 'a092a63a88a7e3f1cdd08ffca82ba53c'
    TRACKER_PROJECT_ID = '1544689'

    PivotalTracker::Client.token = TRACKER_TOKEN
    PivotalTracker::Client.use_ssl = true

    unpakt_project = PivotalTracker::Project.find(TRACKER_PROJECT_ID)
    stories = unpakt_project.stories.all(:state => "finished", :story_type => ['bug', 'feature'])

    stories.each do | story |
      puts "Searching for #{story.id} in local git repo."
      search_result = `git log -i --grep "[Finish(es)?|Fix(es)?] ##{story.id}"`
      if search_result.length > 0
        story.notes.create(:text => "Delivered by staging deploy script.")
        story.update({"current_state" => "delivered"})
      end
    end
  end
end
