#!/usr/bin/env ruby

require "open3"
require "nkf"

TargetCode = "UTF-8"

# enforced custom commit message code
# reference url:
#   http://git-scm.com/book/ja/v1/Git-%E3%81%AE%E3%82%AB%E3%82%B9%E3%82%BF%E3%83%9E%E3%82%A4%E3%82%BA-Git-%E3%83%9D%E3%83%AA%E3%82%B7%E3%83%BC%E3%81%AE%E5%AE%9F%E6%96%BD%E4%BE%8B
#
def check_message_code( oldrev, newrev )
  missed_revs = `git rev-list #{oldrev}..#{newrev}`.split("\n")
  missed_revs.each do |rev|
    message = `git cat-file commit #{rev} | sed '1,/^$/d'`
    if checkcode( message, TargetCode ) != 0 then
      puts "[POLICY] Your message is not written in #{TargetCode}."
      exit 1
    else
      exit 0
    end
  end
end

def checkcode( msg, code )
  o, e, s = NKF.guess( msg )
  mojicode = o.to_s
  if mojicode == "BINARY" || mojicode == "ASCII" then
    istatus = 0
  else
    if mojicode == code then
      istatus = 0
    else
      istatus = 1
    end
  end
  return istatus
end

refname = ARGV[0]
oldrev  = ARGV[1]
newrev  = ARGV[2]
user    = ENV['USER']

puts "Enforcing Policies... \n(#{refname}) (#{oldrev[0,6]}) (#{newrev[0,6]})"

check_message_code( oldrev, newrev )
