#!/usr/bin/env perl

# Git prepare-commit-msg hook to help create commit messages according to our
# standards.

use v5.26.0;
use warnings;
use warnings FATAL => qw( recursion );
use experimental "signatures";
use feature "unicode_strings";

use Cwd            qw( abs_path );
use File::Basename qw( dirname );
use lib dirname(abs_path(__FILE__)) . "/lib";
use GitHook qw( get_current_branch on_main ticket_re );

$|++;

my $Ticket_re = ticket_re;

sub get_ticket () { get_current_branch =~ /^($Ticket_re)/ ? $1 : "GH-XXXXX" }

sub main () {
  my ($file, $type) = @ARGV;
  $type //= $ENV{PRE_COMMIT_COMMIT_MSG_SOURCE} // "";

  return 0 if $type !~ /^(?:|message|template|merge)$/;

  my $main   = on_main;
  my $ticket = get_ticket;
  my ($seen_ticket, $seen_scissors);

  local ($^I, @ARGV) = ("", $file);
  while (my $line = <<>>) {
    chomp $line;

    if ($type eq "merge") {
      $line =~ s/^(Merge branch ')($Ticket_re).*/$1$2'/;
      say "" if $. == 2 && $line ne "";
    } else {
      if (!$main) {
        if ($. == 1 && $line eq "") {
          say "\n\nTicket $ticket\n";
          $seen_ticket = 1;
          next;
        }
        if ($. == 3 && !$seen_ticket) {
          $seen_ticket = 1;
          unless ($line =~ /^Ticket $Ticket_re$/) {
            say "Ticket $ticket\n";
          }
        }
      }
      $seen_scissors = 1
        if $line eq "# ------------------------ >8 ------------------------";
    }

    say $line;

    if (eof) {
      say "\nTicket $ticket" if !$main && $type ne "merge" && !$seen_ticket;
      say "#\n# *** HINT ***\n",
        "# Add the -v option to git commit to see your changes here\n",
        '# or run "git config --global commit.verbose true".'
        if !$type && !$seen_scissors;
    }
  }

  0
}

exit main
