#! /usr/bin/env tclsh
#
# genchanges - Generate changes summary for doc/Changes files.
#
# Copyright (C) 2017 Eggheads Development Team
#
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
package require Tcl 8.5

proc show_usage {} {
	puts "Syntax: $::argv0 <show changes since this git tag (e.g. v1.8.0)> \[show changes to this git tag (e.g. v1.8.1)\]"
	puts "normal usage: \"$::argv0 v1.8.0\", then paste the result into doc/Changes1.8"
	exit 1
}

if {[llength $argv] != 1 || [set basecommit [lindex $argv 0]] in {-h --help}} {
	show_usage
}

if {[catch {exec git rev-list $basecommit..HEAD} commits]} {
	puts "Error: git rev-list $basecommit..HEAD returned\n$commits\n"
	exit 1
}

set result ""
foreach commit [lreverse $commits] {
	set fullmsg [exec git show -s --pretty=format:%B $commit]
	set shortmsg [exec git show -s --pretty=format:%s $commit]
	set date [clock format [exec git show -s --pretty=format:%ct $commit] -gmt 1 -format "%Y-%m-%d"]
	set found ""
	set patch ""
	foreach {- category names} [regexp -nocase -all -inline -- {(found|patch) by:([^\r\n/]+)} $fullmsg] {
		foreach nick [split $names {, }] {
			set nick [string trim $nick ""]
			if {$nick ne ""} {
				dict set [string tolower $category] $nick 1
			}
		}
	}
	set secondline ""
	if {[dict size $found]} {
		lappend secondline "Found by: [join [dict keys $found] {, }]"
	}
	if {[dict size $patch]} {
		lappend secondline "Patch by: [join [dict keys $patch] {, }]"
	}
	if {[llength $secondline]} {
		append shortmsg "\n  [string repeat " " 10] [join $secondline { / }]"
	}
	lappend result "  $date $shortmsg"
}
puts [join [lreverse $result] \n\n]
