#!/usr/bin/env ruby

#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments.  The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-commit".

#system( "git log -l --name-only --pretty=format:""" )
#system( "git show HEAD" )

require "open3"

TargetCode = "UTF-8"

def checkcode( mojicode, code )
  if mojicode == "BINARY" || mojicode == "ASCII" || mojicode == "" then
    istatus = 0
  else
    if mojicode == code then
      istatus = 0
    else
      istatus = 1
    end
  end
  return istatus
end

o, e, s = Open3.capture3( "git rev-parse --verify HEAD" )
if s == 0 then
#  against = "HEAD"
  against = o.chomp
else
  against = "4b825dc642cb6eb9a060e54bf8d69288fbee4904" # mean empty tree
  puts "Unexpected else."
  exit 1
end

o, e, s = Open3.capture3( "git diff #{against} --name-only --pretty=format:""" )
fns = o.split("\n")
fns.each do |fn|
  o, e, s = Open3.capture3( "nkf -g #{fn}" )
  mojicode = o.to_s.chomp
  istatus = checkcode( mojicode, TargetCode )
  if istatus != 0 then
    puts "[POLICY] A file, #{fn}, is not written in #{TargetCode}, but in #{mojicode}."
    exit 1
  end
end
