#!/usr/bin/perl

use warnings;
use strict;

use Getopt::Long;
use Topbloke;

Getopt::Long::Configure(qw(bundling));

die "bad usage\n" unless @ARGV==1;

our $spec = parse_branch_spec($ARGV[0]);
our $current = current_tb_branch();

die "cannot make branch starting at base of another;".
    " check out a real branch\n" if $current->{Kind} eq 'base';

die "strange branch ref $current->{Kind} $current->{Ref},\n".
    " making new branch with this as dep is unwise\n"
    unless ($current->{Kind} eq 'foreign' ||
	    $current->{Kind} eq 'tip');

sub fillin ($$$) {
    my ($key, $newval, $what) = @_;
    return if defined $spec->{$key};
    $spec->{$key} = $newval;
}

if (!defined $spec->{Email} || !defined $spec->{Domain}) {
    my $eaddr = run_git_1line(qw(config user.email));
    $eaddr =~ m/^(.*)\@/ or die "$eaddr ?";
    fillin('Email',$1,'email domain');
    fillin('Domain',$','email domain'); #');
}

if (!defined $spec->{Date}) {
    $spec->{Date} = `LC_TIME=C date -u +%Y-%m-%dT%H%M%SZ`;
    chomp $spec->{Date} or die $!;
}

length($spec->{Date})==18 or die "partial date specified, not supported\n";

check_no_unwanted_metadata('HEAD')
    if $current->{Kind} ne 'tip';

# For the metadata files in .topbloke, we hope that the user
# doesn't modify them.  If they do then they get to keep all the pieces.
#
# For .topbloke/msg, if it's modified by the user (ie, if working
# version differs from HEAD) we keep that, and we stage it unless
# the cached version differs from the HEAD.

my $newbranch = "$spec->{Email}\@$spec->{Domain}/$spec->{Date}/$spec->{Nick}";

$newbranch = run_git_1line(qw(check-ref-format --print), $newbranch);

printf "creating %s\n", $newbranch;

setup_config();

if (!run_git_test_anyoutput(qw(diff --name-only HEAD -- .topbloke/msg)) {
    open NM, '>', ".topbloke/msg.tmp" or die $!;
    my $author = run_git_1line(qw(var GIT_AUTHOR_IDENT));
    $author =~ s/ \d+ [-+]\d+$//;
    print NM "From: $author\n" or die $!;
    foreach my $h (qw(To CC BCC)) {
	my $estatus;
	run_git(\$estatus, sub { print NM "$h: $_" or die $!; },
		qw(config), "topbloke.".lc $h);
	die "$h $estatus" unless $estatus==0 || $estatus==256;
    }
    $subjprefix = git_config('topbloke.subjectprefix', '');
    print NM <END or die $!;
Subject: [${subprefix}PATCH] $spec->{Nick}

<patch description>

Signed-off-by: $author
END
    run_git(qw(add .topbloke/msg));
    print " created and staged new .topbloke/msg\n";
} else {
    if (!run_git_test_anyoutput(qw(diff --cached --name-only HEAD --
				   .topblokemsg))) {
	print " staged your modified .topbloke/msg\n";
	run_git(qw(add .topbloke/msg));
    } else {
	print " left your (partially staged?) .topbloke/msg\n";
    }
}

