#!/usr/bin/env python

from commands import getoutput
from os import path, environ, system
import sys
from datetime import date
from shutil import copy
import re

cl_name = environ.get('CHANGE_LOG_NAME')
cl_email = environ.get('CHANGE_LOG_EMAIL_ADDRESS')
editor = environ.get('EDITOR')

if not path.isdir('./.git'):
    print 'Not the root of the repository'
    sys.exit(-1)
    
# File paths starting with ".." are not useful here
fname_exp = '(?P<fname>[^.\s]([^.]|\Z).*)'
# "#	modified:  my/modified/file/name"
modified_line_exp = '#(\s\S+)+:\s+%s\Z' % fname_exp

paths = {}

for line in getoutput('git status').split('\n'):
    if line == '# Changed but not updated:':
        break

    m = re.search(modified_line_exp, line)
    if m is None:
        continue

    fname = m.group('fname')
    p = fname.rpartition ('/')
    if p[0] == '':
        directory = './'
    else:
        directory = p[0] + p[1]

    if not paths.has_key (directory):
        paths[directory] = []

    paths[directory].append (p[2])

for item in paths.iteritems():
    cl = item[0] + 'ChangeLog'
    if not path.isfile (cl):
        continue
    
    tmp = item[0] + '.ChangeLog_save'
    copy(cl, tmp)

    f = open (cl, 'r')
    content = f.read()
    f.close()

    f = open (cl, 'w')
    
    output = []
    output.append("%s  %s  <%s>\n\n" % (date.today().strftime('%Y-%m-%d'), cl_name, cl_email))
    for entry in item[1]:
        output.append("\t* %s:\n" % entry)

    f.writelines(output)
    f.write ('\n')
    f.write(content)
    f.flush()

    system (editor + ' ' + cl)
