The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
#!/usr/bin/perl
use warnings;
use strict;

use version; our $VERSION = qv('1.3.13');

use FindBin;
use lib "$FindBin::Bin/../lib/perl5";
use File::Temp qw( tempfile );
use Narada::Config qw(get_config_line);

## no critic (ProhibitEscapedCharacters)
our $NORM   = "\033[0m";
our $BOLD   = "\033[1m";
our $BLINK  = "\033[5m";
our $REV    = "\033[7m";
our $BLACK  = "\033[30m";
our $RED    = "\033[31m";
our $GREEN  = "\033[32m";
our $YELLOW = "\033[33m";
our $BLUE   = "\033[34m";
our $MAGENTA= "\033[35m";
our $CYAN   = "\033[36m";
our $WHITE  = "\033[37m";
## use critic (ProhibitEscapedCharacters)

local $SIG{INT} = sub { exit };  # cleanup temp files
local $SIG{QUIT}= sub { exit };  # cleanup temp files
main(@ARGV) unless caller;    ## no critic (ProhibitPostfixControls)


sub err { die "narada-patch: @_\n" }; ## no critic (ProhibitBuiltinHomonyms)
sub color_die {
    my ($msg) = @_;
    $msg =~ s/\A/$BOLD$RED/xms;
    $msg =~ s/\Z/$NORM/xms;
    err $msg;
    return;
}
sub color_warn {
    my ($msg) = @_;
    $msg =~ s/\A/$BOLD$RED * $NORM/xms;
    warn $msg;  ## no critic (RequireCarping)
    return;
}
sub color_printf {
    my ($fmt, @arg) = @_;
    my $msg = sprintf $fmt, @arg;
    $msg =~ s/\A/$BOLD$GREEN * $NORM/xms;
    printf $msg;
    return;
}
sub bold  { my ($s) = @_; return $BOLD.$WHITE.($s||q{}).$NORM }
sub bold2 { my ($s) = @_; return $BOLD.$CYAN. ($s||q{}).$NORM }
sub pause {
    my ($s) = @_;
    local $|=1;
    print "\n",$BOLD,$YELLOW,$s,$NORM;
    return scalar <STDIN>;
}
sub basename {
    my ($file) = @_;
    $file =~ s{.*/}{}xms;
    return $file;
}

sub main {
    rename 'var/patch/prev', 'var/patch/.prev'; # compatibility with Narada <1.2.0
    die "Usage: narada-patch\n"
        if @_ > 1
        || (@_ == 1 && $_[0] ne '--no-prev'); # compatibility with Narada <0.9.3
    my %patches = get_patches('var/patch');
    apply_patches(undef, q{.}, %patches);
    if (-f 'var/patch/.prev/config/version') {
        apply_patches(undef, 'var/patch/.prev', %patches);
    }
    for my $addon (map {m{/([^/]+)/\z}ms} glob 'var/patch/*/') {
        %patches = get_patches("var/patch/$addon");
        apply_patches($addon, q{.}, %patches);
    }
    return;
}

sub read_file {
    my ($file) = @_;
    open my $f, '<', $file              or err "open($file): $!";
    local $/ = undef;
    my $val = <$f>;
    close $f                            or err "close: $!";
    return $val;
}

sub replace_addon_patch {
    my ($addon, $file) = @_;
    my $patch = read_file($file);
    my $rename= qr{(?:config/version|doc/ChangeLog)(?=\s)}ms;
    $patch =~ s{^(diff [^\n]*/$rename)([^\n]*/$rename)}{$1.$addon$2.$addon}msg;
    $patch =~ s{^((?:[+-]{3}) [^\n]*/$rename)}{$1.$addon}msg;
    my ($fh, $tempfile) = tempfile(UNLINK=>1);
    print {$fh} $patch;
    close $fh                           or err "close: $!";
    return $tempfile;
}

sub apply_patches {
    my ($addon, $dir, %patch_for) = @_;
    chomp(my $pwd = `pwd`);
    chdir $dir or err "chdir: $!";
    printf "\n";
    color_printf "\n";
    if (defined $addon) {
        color_printf "Patching directory: %s (addon %s)\n", bold($dir), bold($addon);
    } else {
        color_printf "Patching directory: %s\n", bold($dir);
    }
    color_printf "\n";
    my $v=get_config_line(defined $addon ? "version.$addon" : 'version');
    while (exists $patch_for{$v}) {
        printf "\n";
        color_printf "Current version: %s\n", bold($v);
        my $patch = $patch_for{$v};
        my @files = sort glob "$patch.*";
        for my $file (@files) {
            color_printf "Applying %s ...\n", bold2(basename($file));
            my ($ext) = $file =~ /.*[.](.*)/xms;
            if ($ext eq 'patch') {
                if (defined $addon && $file =~ /[.]99[.]patch\z/ms) {
                    $file = replace_addon_patch($addon, $file);
                }
                color_printf "--- DRY RUN, NO FILES WILL BE MODIFIED ---\n";
                my $status = system "patch -p1 --dry-run < \Q$file\E";
                if ($status != 0) {
                    pause('Press Enter to REALLY apply this file...');
                }
                color_printf "--- REAL RUN, MODIFYING FILES ---\n";
                system "patch -p1 < \Q$file\E";
            }
            elsif ($ext eq 'tgz') {
                my $TAR = (grep {-x "$_/gtar"} split /:/ms, $ENV{PATH}) ? 'gtar' : 'tar';
                system "$TAR xzvf \Q$file\E";
            }
            elsif ($ext eq 'sql') {
                system "narada-mysql < \Q$file\E";
            }
            elsif ($ext eq 'sh') {
                system "bash -x \Q$file\E";
            }
            elsif ($ext eq 'pl') {
                system "perl \Q$file\E";
            }
            else {
                color_warn("Don't know how to apply: $file");
            }
        }
        $v=get_config_line(defined $addon ? "version.$addon" : 'version');
    }
    chdir $pwd or err "chdir: $!";
    return;
}

sub get_patches {
    my ($dir) = @_;
    my %patch_for;  # Found patches, key - version "from", value - file name
    chomp(my $pwd = `pwd`);
    printf "\n";
    for my $file (glob "$pwd/$dir/*.99.patch") {
        my $patch = read_file($file);
        if ($patch !~ m{^diff\s+\S+\s+\S+config/version\s+[^\n]+\n
                        ---         \s+[^\n]+\n
                        [+][+][+]   \s+[^\n]+\n
                        @[^\n]+\n
                        (?:-   ([^\n]+)\n)?
                        }xms) { ## no critic (ProhibitComplexRegexes)
            color_warn "Unable to detect version in '$file', skipping...\n";
        }
        else {
            my $ver = $1;
            if (exists $patch_for{$ver}) {
                color_die "Found two patches for same version!\n"
                  . "\tVersion: $ver\n"
                  . "\tPatch1: $patch_for{$ver}\n"
                  . "\tPatch2: $file\n";
            }
            $file =~ s/[.]99[.]patch\z//xms;
            $patch_for{$ver} = $file;
        }
    }
    for (sort keys %patch_for) {
        color_printf "Found patch: %-33s -> %s\n",
            bold($_), basename($patch_for{$_});
    }
    return %patch_for;
}


1; # Magic true value required at end of module

## no critic (RequirePodAtEnd)

=head1 NAME

narada-patch - apply pending patches on Narada project


=head1 VERSION

This document describes narada-patch version 1.3.13


=head1 USAGE

    narada-patch


=head1 DESCRIPTION

Apply updates found in C<var/patch/*> files on both project root and
C<var/patch/.prev/>. Then apply addon updates in C<var/patch/*/*> files on
project root. Automatically detect which updates should be applied.
Update may include C<.sh>, C<.patch>, C<.tgz>, C<.sql> and C<.pl> files.


=head1 REQUIRED ARGUMENTS

None.

=head1 OPTIONS

See USAGE.

=head1 CONFIGURATION AND ENVIRONMENT

None.

=head1 DEPENDENCIES

None.

=head1 INCOMPATIBILITIES

None reported.

=head1 BUGS AND LIMITATIONS

No bugs have been reported.

Please report any bugs or feature requests to
C<bug-narada@rt.cpan.org>, or through the web interface at
L<http://rt.cpan.org>.


=head1 AUTHOR

Alex Efros  C<< <powerman@cpan.org> >>


=head1 LICENSE AND COPYRIGHT

Copyright (c) 2008-2014 Alex Efros C<< <powerman@cpan.org> >>. All rights reserved.

This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself. See L<perlartistic>.


=head1 DISCLAIMER OF WARRANTY

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.