#!/usr/bin/env perl
use strict;
use warnings;
use Mojo::File qw'path';
use Mojo::Util qw!extract_usage!;
use feature 'say';
use DateTime;
use Getopt::Long;

GetOptions (
  "help|h" => sub {
    say "--quarter (show statistics for a quarter instead of a month)";
    say "--current (show statistics for the current instead of the last unit)";
    say "--user []";
    say extract_usage;
    exit(0);
  },
  "quarter|q" => \(my $quarter),
  "current|c" => \(my $current),
  "user|u=s"  => \(my $user)
);

# Get the relevant timeslice
my $dt = DateTime->now;
if (!$current && !$quarter) {
  $dt->subtract(months => 1);
}
elsif ($quarter) {
  if ($dt->month <= 3) {
    $dt->set_month(1);
  }
  elsif ($dt->month <= 6) {
    $dt->set_month(4);
  }
  elsif ($dt->month <= 9) {
    $dt->set_month(7);
  }
  else {
    $dt->set_month(10);
  };

  if (!$current) {
    $dt->subtract(months => 3);
  };
};

my $year = $dt->year;
my $from = $dt->month_abbr;

if ($quarter) {
  $dt->add(months => 2);
};

my $to = $dt->month_abbr;

my $cmd = "git shortlog -sne " .
  "--since='01 $from $year' " .
  "--before='31 $to $year' " .
  "--no-merges " .
  "--max-parents=1";

my $sum = 0;
my @components = ();

my $file = path(path(__FILE__)->dirname, 'count_commits.conf');
my @lines = split "\n", $file->slurp;

if ($lines[0] =~ /^\[([^\]]+?)\]$/) {
  $user ||= $1;
  shift @lines;
};

unless ($user) {
  die 'No user defined';
};

say "\nCommits from 01 $from $year - 31 $to $year by $user";
say "------";

foreach (@lines) {
  chomp $_;
  my $dir = path($_);
  my $dir_str = $dir->to_string;
  if (-d $dir_str) {
    chdir $dir_str;
    my $out = `$cmd`;
    if ($out =~ /\s+(\d+)\s+$user/) {
      $sum += $1;
      say $dir->basename, ": $1";
      push @components, [ $dir->basename => $1 ];
    };
  } else {
    warn "$dir does not exist\n";
  }
};

say '------';
say "Commits: $sum";
say "In: " . join(', ', map { $_->[0] } sort { $b->[1] <=> $a->[1] } @components),"\n";

exit(0);

__END__

=pod

=head1 SYNOPSIS

  Usage: count_commits --quarter --current --user Akron

=head1 DESCRIPTION

This script will count and sum up all commits
in all repositories listed in the configured repositories
for a certain user in the current branches.

The configuration file is expected in the same folder as the script
and named C<count_commits.conf>.

It has the following structure:

  [Username]
  /path/to/my/repo1
  /path/to/my/repo2
  ...

The username has to be in the first line and written in square brackets.

Two different time ranges are supported:

Per default the last finished month
is listed. With the parameter C<--quarter>, the last quarter are listed.

With the parameter C<--current> the current month or quarter is taken into account.

The username can be overwritten with the C<--user> parameter.

=cut
