#!/usr/bin/env perl
#***********************************************************************
# This file is part of OpenMolcas.                                     *
#                                                                      *
# OpenMolcas is free software; you can redistribute it and/or modify   *
# it under the terms of the GNU Lesser General Public License, v. 2.1. *
# OpenMolcas is distributed in the hope that it will be useful, but it *
# is provided "as is" and without any express or implied warranties.   *
# For more details see the full text of the license in the file        *
# LICENSE or in <http://www.gnu.org/licenses/>.                        *
#                                                                      *
# Copyright (C) 2013, Steven Vancoillie                                *
#***********************************************************************
#
# changelog
#
# Program that gives an overview of the changes introduced in
# each of the stable snapshots.
#
# Used with Molcas to give a list of all master branch snapshots
# (tagged with e.g. master-13-07-17), and list the changes and
# their descriptions.
#
# Steven Vancoillie, August 2013

use File::Basename;

my $MOLCAS_DRIVER;
$MOLCAS_DRIVER = $ENV{"MOLCAS_DRIVER"} or $MOLCAS_DRIVER = "molcas";
my $DRIVER_base = basename($MOLCAS_DRIVER);

my $MOLCAS=$ENV{"MOLCAS"};
die "MOLCAS not set, use $DRIVER_base changelog\n" unless ($MOLCAS);

# if this is a git repo, sanity check if git exists,
# otherwise print a warning.
my $git_exists = 0;
foreach my $path (split /:/, $ENV{'PATH'}) {
    if ( -f "$path/git" && -x _ ) {
        $git_exists = 1;
        last;
    }
}
if ( not -e "$MOLCAS/.git" or not $git_exists) {
    print "Error: git not available or not a git repo\n";
    exit 1;
}

# check for option -n, where n is the number of changelogs
# to show, and store that number in $limit
my $limit;
my $head;
while (my $opt = shift @ARGV) {
    if ($opt =~ /^master-/) {
        $head = $opt;
    }
    if ($opt =~ /^-(\d+)/) {
        $limit = $1;
    }
}

# get list of master tags
my @tags = reverse sort grep /^master-/, `git tag --list`;
chomp @tags;

if (defined $head) {
    while (my $tag = shift @tags) {
        if ($tag =~ $head) {
            unshift @tags, $tag;
            last;
        }
    }
}

# set a limit for the number of changelogs to display
# default behaviour is to display all changelogs
my $total = $#tags - 1;
my $stop = $total;
if ($limit) {
    $stop = $limit > $total ? $total : $limit - 1;
}

# display the changelogs
for my $index (0 .. $stop) {
    $curr = $tags[$index];
    $prev = $tags[$index+1];
    print "CHANGELOG $curr\n";
    print "\n";
    print `git log --no-merges --date-order --format=" %s" $prev..$curr`;
    print "\n";
    print `git diff --stat $prev $curr`;
    print "\n";
}

exit 0;
