#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
#--
#   Copyright (C) 2008 Johan Sørensen <johan@johansorensen.com>
#   Copyright (C) 2009 Marius Mårnes Mathiesen <marius.mathiesen@gmail.com>
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU Affero General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU Affero General Public License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#++
print "=> Syncing Gitorious... "

incpath = File.dirname(__FILE__)
$: << incpath

require 'messaging'

@publisher = Publisher.new
gitdir = File.expand_path(File.join(incpath, ".."))

# Equivalent to the hash in the model
hashed_dir = gitdir.split('/')[-3,3].join('/').split('.').first

# compat with the old-style paths
hashed_dir = hashed_dir.sub(/^repositories\//, "")

hook_input_lines = ""

while line = gets
  hook_input_lines << line
  @publisher.post_message({:gitdir => hashed_dir, :message => line.chomp, :username => ENV['GITORIOUS_USER']})
end

require 'pathname'
def custom_hook_path
  real_path_of_this = Pathname.new(File.dirname(__FILE__)).realpath
  full_path_of_this = File.expand_path(real_path_of_this)
  custom_prereceive_path = full_path_of_this + "/custom-post-receive"
end

def run_custom_hook_if_present(input)
  if (File.exist?(custom_hook_path) && File.executable?(custom_hook_path))
    cmd = %Q{#{custom_hook_path} 2>&1}
    IO.popen(cmd, 'w+') do |subprocess|
      subprocess.write(input)
      subprocess.close_write
      subprocess.read.split("\n").each do |l|
        puts "#{l}\n"
      end
    end

    custom_hook_status = $?
    if !custom_hook_status.success?
      puts "not success, exiting with its code"
      exit(custom_hook_status.exitstatus)
    end
  end  
end

run_custom_hook_if_present(hook_input_lines)

puts "[OK]"
