#!/usr/bin/perl

use Modern::Perl;

use File::Slurp;
use Pod::Usage;
use Getopt::Long;

use Koha;

my ( $help, $verbose, @files );
GetOptions(
    'h|help'                 => \$help,
    'v|verbose'              => \$verbose,
) || pod2usage(1);

@files = @ARGV;

pod2usage(1) if $help or not @files;

my $updatedatabase_path = 'installer/data/mysql/updatedatabase.pl';
my $atomicupdate_path = 'installer/data/mysql/atomicupdate/';
my $Kohapm_path = 'Koha.pm';
my @updatedatabase_lines = read_file $updatedatabase_path;
my ( @updatedatabase_begin, @updatedatabase_end );;
my $koha_version = Koha::version;
my ( $last_chunk_found, $end );
for my $line ( @updatedatabase_lines ) {
    $last_chunk_found = 1 if $line =~ m|^\$DBversion = '$koha_version'|;

    unless ( $last_chunk_found ) {
        push @updatedatabase_begin, $line;
        next;
    }

    if ( !$end ) {
        push @updatedatabase_begin, $line;
        $end = 1 if $line =~ m|^}$|;
        next;
    }

    push @updatedatabase_end, $line;
}

for my $file (@files) {
    say "Processing $file";

    $file = $atomicupdate_path . $file unless -f $file;
    my @new_lines = read_file $file;

    $koha_version = increment_version($koha_version);
    $new_lines[0] = sprintf "\$DBversion = '%s';\n", $koha_version;
    push @updatedatabase_begin, "\n";
    push @updatedatabase_begin, @new_lines;

    my ($bug_number) = ( $new_lines[-2] =~ m|(\d{4,5})| );

    my $Kohapm = read_file $Kohapm_path;
    $Kohapm =~ s|VERSION = "\d{2}.\d{2}.\d{2}.\d{3}";|VERSION = "$koha_version";|;
    write_file $Kohapm_path, $Kohapm;

    write_file $updatedatabase_path, @updatedatabase_begin, @updatedatabase_end;

    qx{git rm $file};
    qx{git add $Kohapm_path};
    qx{git add $updatedatabase_path};
    qx{git commit -m"Bug $bug_number: DBRev $koha_version"};
}

sub increment_version {
    my ( $current_version ) = @_;
    #20.06.00.016
    my ( $prefix, $minor ) = ( $current_version =~ m|(\d{2}\.\d{2}\.\d{2}\.)(\d{3}$)| );
    $minor++;
    return "$prefix$minor";
}
