#!/usr/bin/env perl

# Creates and sets up the Database for installation of Juice.

use strict;
use warnings;
use Env qw(PORTAL JUICEDIR);
use File::Slurper qw(read_text);
use TOML qw(from_toml);
use English qw( -no_match_vars );
use DBI;
use File::Basename qw(fileparse);
use Text::CSV;
# use Data::Dumper;
use v5.12;

# Check if ENV Varables are set.
die 'Error: portal not defined, cannot continue' if (!defined $PORTAL);
die 'Error: Juice install path not set, cannont contine' if (!defined $JUICEDIR);

my $tomlPath = "$JUICEDIR/config.toml";
my $toml = read_text($tomlPath);
my ($data, $err) = from_toml($toml);
unless ($data) {
  die "Error: failed parsing toml: $err";
}

my $master_db = $data->{'database'}->{'master'};
system("mysql -u$master_db->{'user'} -p$master_db->{'passwd'} $master_db->{'name'} < $JUICEDIR/database/schema.sql")
  and die "Error: could not import database schema\n";
my $dsn = "DBI:$master_db->{'driver'}:database=$master_db->{'name'}:port=$master_db->{'port'}";
my $dbh = DBI->connect($dsn, $master_db->{'user'}, $master_db->{'passwd'}, {'RaiseError' => 1})
  or die "Error: Could not connect to the database: $OS_ERROR\n";

my $dataDir = "$JUICEDIR/database/data";
opendir(my $dh, $dataDir) || die "Error: failed reading $JUICEDIR/database/data directory\n";
while(readdir $dh) {
  if ($ARG ne '.' and $ARG ne '..') {
    say "Importing data from $ARG";
    import_to_table($dbh, "$dataDir/$ARG");
  }
}
closedir $dh;

$dbh->disconnect or warn $dbh->errstr;

exit 0;

sub import_to_table {
  my ($dbh, $file) = @ARG;

  my $table = get_table_name($file);
  open my $io, '<:encoding(UTF-8)', $file or die "Error: cannot open file $file: $OS_ERROR";
  my $csv = Text::CSV->new({ binary => 1 })
    or die "Error: cannot use CSV: " . Text::CSV->error_diag();

  $dbh->{AutoCommit} = 0;
  my $i = 0;
  my $fields;
  my @fields;
  my $placeholders;
  eval {
    while (my $row = $csv->getline ($io)) {
      if ($i == 0) {
        @fields = @$row;
        $fields = join ', ', @fields;
        $placeholders = '(' . join(', ', ('?') x @fields) . ')';
        $i++;
        next;
      }

      my @data = @$row;
      # Replace portal placeholder with $PORTAL
      foreach (@data) {
        s/%portal%/$PORTAL/;
      }

      $dbh->do("INSERT INTO $table ($fields) VALUES $placeholders", {}, @data);
      undef @data;
    }
  };
  if ($OS_ERROR) {
    warn "Transaction abored because $OS_ERROR";
    eval { $dbh->rollabck };
    if ($OS_ERROR) {
      die "Transaction failed and rollback failed: $OS_ERROR\n";
    }
  }
  $dbh->commit;
  $dbh->{AutoCommit} = 1;
}

sub get_table_name {
  my ($path) = shift;

  my $filename = fileparse($path, qr/\.[^.]*/);
  return $filename;
}
