#!/usr/bin/env ruby

require 'rubygems'
gem 'tinder'
require 'tinder'

repo = ENV['SSH_ORIGINAL_COMMAND'].split(" ")[1]

campfire = Tinder::Campfire.new 'hoover'
campfire.login 'email', 'pass'
room = campfire.rooms[0] # can also do rooms.select { |r| room.name == 'foo' }

GIT = `which git`.strip

filename = File.join(File.dirname(__FILE__), repo[/[\w.]+/] + ".log")
if File.exist?(filename)
last_revision = Time.parse File.open(filename) { |f| f.read.strip }
else
room.speak "Debug: Couldn't find previous revision file"
last_revision = Time.now - 5
end

text = `#{GIT} log --all --since="#{last_revision}"`

# revision = `#{GIT} log -1 --all | sed -e 's/commit //' -e '2,$d'`.chomp

File.open(filename, "w+") { |f| f.write Time.now.utc }

lines = text.split("\n\ncommit ")
room.speak "Updated #{lines.size} commits since #{last_revision}"
lines.each do |line|

revision = line[/([a-f0-9]{32})/]

commit_author = `#{GIT} show --pretty=format:"%an" #{revision} | sed q`.chomp
commit_log = `#{GIT} show --pretty=format:"%s" #{revision} | sed q`.chomp
commit_date = `#{GIT} show --pretty=format:"%aD" #{revision} | sed q`.chomp
commit_changed = `#{GIT}-diff-tree --name-status #{revision} | sed -n '$p'`

commit_changes = commit_changed.split("\n").inject([]) do |memo, line|
if line.strip =~ /(\w)\s+(.*)/
memo << [$1, $2]
end
end.to_yaml


room.speak "#{commit_author}: #{repo}:..#{revision.last(5)} >> #{commit_log}"
room.paste commit_changed

end