#!/usr/local/bin/perl

use perl5i::2;
use File::Copy;

my $Remote_Store = 'schwern.net:~/schwern.org/src/';
my $Local_Store  = "$ENV{HOME}/releases/";

my %Is;

my $builder;
my $build_file;
my @build_args;


# I guess this is useless with perl5i
sub run {
    system(@_) == 0 or exit $? >> 8;
}


sub cat {
    my $file = shift;
    open my $fh, "<", $file;
    return join '', <$fh>;
}


# Check the current branch is master and pause to correct if not
sub check_branch {
    return 1 unless $Is{git};
    return 1 if cat("$Is{git}/HEAD") =~ m{^ref: refs/heads/master\n};

    print STDERR "\a\a";
    warn "Releasing non-master branch!\n";
    sleep 2;

    return;
}


# Answer MakeMaker prompts with their defaults
$ENV{PERL_MM_USE_DEFAULT} = 1;

# Used by some of my modules to indiciate this is a release
$ENV{PERL_RELEASING}      = 0;

# Used by tests to indicate running the full author tests
$ENV{AUTHOR_TESTING}      = 'MSCHWERN';


# Look for git
my @gits = qw(.git ../.git ../../.git);
$Is{git}        = @gits->first(sub { -d $_ });

# Look for git-svn, but a live git-svn, not just a left over
$Is{'git-svn'}  = glob("$Is{git}/svn/*");

# Use MB or EUMM?
-e "Build.PL" ? $Is{'Module::Build'} = 1 
              : $Is{'MakeMaker'}     = 1;

check_branch();

# Build with signatures
if( $Is{'Module::Build'} ) {
    $builder    = './Build';
    $build_file = 'Build.PL';
    @build_args = qw(--sign 1);
}
else {
    $builder    = 'make';
    $build_file = 'Makefile.PL';
    @build_args = qw(SIGN=1);
}

# Build it, rebuild the manifest, test a clean distribution, build a dist
run("$^X $build_file @build_args");
run("$builder manifest");
run("$builder disttest");
run("$builder dist");

# Find the release tarball
my @tarballs = glob("*.tar.gz");
die "More than one tarball" if @tarballs > 1;
die "No tarball?" if @tarballs == 0;

my $dist = $tarballs[0];

# Upload to CPAN
run("cpan-upload -verbose $dist");

# Parse the version from the tarball name
my($version) = $dist =~ m{-v?([\d\._]+)\.tar\.gz};
print "Released $version\n";

# Commit, tag and push changes
if( $Is{git} ) {
    run(qq[git commit -a -m 'Version $version']);

    my $tag = "v$version";
    run("git tag $tag -a -m 'Version $version released to CPAN'");

    if( $Is{'git-svn'} ) {
        # XXX Not sure how to push the tag with git-svn
        run("git svnpush");
    }
    else {
        run("git push origin");
        run("git push origin $tag");
    }
}

# Store a copy of the tarball remotely and locally
run("scp $dist $Remote_Store") if $Remote_Store;
move($dist,    $Local_Store)   if $Local_Store;
