#!/usr/bin/perl

use constant 'DBDIR' => '/var/app/orchard/database';

use strict;
use warnings;
use open ':std', ':encoding(UTF-8)';

use Git;
use JSON::XS;
use FileHandle;
use File::Basename;
use Text::CSV::Easy(qw/csv_build csv_parse/);
use Getopt::Long::Descriptive(qw/describe_options/);

use lib '/var/app/orchard/collab/jgetter/perllib';
use Orchard::Session;
use Orchard::RunCommand;
use Orchard::YamlConfig;
use Orchard::DB::Connect;

my ( $opt, $usage ) = describe_options(
    '%c %o <some-arg>',
    [ 'execute|e=i'    => 'Execute mvn command', { 'default' => 1 } ],
    [ 'killRollback|k' => 'Kill rollback data',  { 'default' => 0 } ],
    [ 'rollback|r=i'   => 'Rollback DB PR - must have rollback count' ],
    [ 'schema|s=s'     => 'Schema for DB PR - default art_relations', { 'default' => 'art_relations' } ],
    [ 'file|f=s'       => 'File to run mvn commands with' ],
    [ 'update|u'       => 'Update database with DB PR' ],
    [ 'help|?|h'       => "print usage message and exit" ]
);

if ( $opt->help ) {
    print $usage->text . "\n";
    exit;
}

if ( not $opt->update and not $opt->rollback ) {
    print "update or rollback is required\n";
    exit;
}

my $schema   = $opt->schema eq 'ra' ? 'royalty_accounting' : $opt->schema;
my $buildDir = DBDIR . "/$schema/build";
my $repoDir  = "$buildDir/changelog";

my $mvn;
if ( $opt->schema eq 'neo' ) {
    $buildDir = DBDIR . "/neo4j/neo4j-orchard/build";
    $repoDir  = "$buildDir/changelog";
    $mvn      = 'mvn -f pom.xml initialize package -DchangeLogFile=';
} else {
    if ( $opt->update ) {
        if ( $opt->killrollback ) {
            my $dsn = Orchard::DB::Connect->dsn('orchdev');
            my $dbh = DBI->connect( @{ $dsn->{'conn'} } ) || die "Conn: $DBI::errstr";
            $dbh->do('DROP TABLE IF EXISTS DATABASECHANGELOG');
            $dbh->do('DROP TABLE IF EXISTS DATABASECHANGELOGLOCK');
        }
        $mvn = 'mvn initialize liquibase:update -DchangeLogFile=';
    } else {
        my $rollbacks = $opt->rollback;
        $mvn = "mvn initialize liquibase:rollback -Dliquibase.rollbackCount=${rollbacks} -DchangeLogFile=";
    }
## -Dorg.slf4j.simpleLogger.defaultLogLevel=DEBUG
}

my $files;
if ( $opt->file ) {
    my $path = $opt->file;
    $path =~ s!.*changelog/!!;
    push @{$files}, $path;
} else {
    my $repo = Git->repository($repoDir);
    $files = [ $repo->command( 'status', '-s' ) ];
}

if ( scalar @{$files} ) {
    foreach my $file ( @{$files} ) {
        next if $file =~ m/.*pom.xml.*/;
        my $buildFile = $file;
        my $cmd;
        if ( not $opt->file ) {
            my ( $state, $gitfile ) = split " ", $file;
            if ( $opt->schema ne 'neo' ) {
                $buildFile = "changelog/$gitfile";
                $cmd       = "cd $buildDir && ${mvn}/$buildFile";
            } else {
                my ($basename) = File::Basename::basename($file);
                $buildFile = $basename;
                $cmd       = "cd $buildDir && ${mvn}$buildFile";
            }
        } else {
            $cmd = "cd $buildDir && ${mvn}$buildFile";
        }
        print "$cmd\n";
        system($cmd) if $opt->execute;
    }
} else {
    print "No updated git files found\n";
    exit;
}
