#!/usr/bin/php
<?php

$sapi = strtolower(php_sapi_name());
if ( 'cli' != $sapi ) {
	g2c_exit('Please run git2cl from the command line');
}

if ( 1 == $argc ) {
	$gitPath = '.';
} else {
	$gitPath = $argv[1];
}

$gitPathEscaped = escapeshellarg($gitPath);
$gitLog = shell_exec("cd {$gitPathEscaped}; git log --date=short --format=%an%n%ae%n%ai%n%s%n###");
$gitLogBits = explode('###' . PHP_EOL, $gitLog);

$gitRealPath = realpath($gitPath);
$changeLogPath = "{$gitRealPath}/ChangeLog";

$changeLog = array();
date_default_timezone_set('America/Chicago');

foreach ( $gitLogBits as $log ) {
	$log = trim($log);
	$bits = explode(PHP_EOL, $log);
	
	if ( count($bits) > 1 ) {
		$author = $bits[0];
		$email = $bits[1];
		$date = $bits[2];
		$message = $bits[3];
		
		$exactDate = date('Y-m-d', strtotime($date));
		$changeLog[$exactDate][] = array(
			'time' => date('H:i:s', strtotime($date)),
			'author' => $author,
			'email' => $email,
			'message' => $message
		);
	}
}

reset($changeLog);

foreach ( $changeLog as $entryDate => $entryList ) {
	fwrite(STDOUT, $entryDate . PHP_EOL);
	foreach ( $entryList as $entry ) {
		fwrite(STDOUT, "\t* {$entry['author']} <{$entry['email']}> {$entry['message']} ({$entry['time']})" . PHP_EOL);
	}
	fwrite(STDOUT, PHP_EOL);
}

function g2c_exit($message) {
	echo $message, PHP_EOL;
	exit(0);
}
