#!/usr/bin/env perl
#
# Exports data from the database into CSV files.

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 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, cannot continue' if (!defined $JUICEDIR);
die 'Error: Table not defined to export, cannot continue' if (!$ARGV[0]);

my $cfg = parseConfig();
my $db = $cfg->{'database'}->{'master'};
my $dsn = "DBI:$db->{'driver'}:database=$db->{'name'}:port=$db->{'port'}";
my $dbh = DBI->connect($dsn, $db->{'user'}, $db->{'passwd'}, {'RaiseError' => 1})
  or die "Error: Could nat connect to the database: $OS_ERROR\n";

export_to_file($dbh, $ARGV[0]);

exit 0;

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

sub export_to_file {
  my ($dbh, $table) = @ARG;

  my $fields = get_table_cols($dbh, $table);
  shift @{$fields} if ($fields->[0] eq 'uniq');
  my $cols = join(', ', @{$fields});
  # say "SELECT $cols FROM $table";
  my $sth = $dbh->prepare("SELECT $cols FROM $table");
  $sth->execute();
  my $csv = Text::CSV->new({ binary => 1 })
    or die "Error: cannot use CSV: " . Text::CSV->error_diag();

  my $filename = get_filename($table);
  unlink $filename if (-e $filename);
  open my $fh, ">:encoding(utf8)", $filename;
  print $fh join(',', @{$fields}) . "\n";
  while(my $ref = $sth->fetchrow_hashref) {
    if (exists $ref->{'portal'} and $ref->{'portal'} eq $PORTAL) {
      $ref->{'portal'} = '%portal%';
    }
    my @row;
    foreach my $field (@{$fields}) {
      push @row, $ref->{$field};
    }

    my $status = $csv->print($fh, \@row);
    print $fh "\n";
    die "Error: Failed writing CSV line: $csv->error_diag\n" if ($status ne 1);
  }
  close $fh;
}

sub get_table_cols {
  my ($dbh, $table) = @ARG;

  my $sth = $dbh->prepare("SELECT * FROM $table WHERE 1=0");
  $sth->execute();
  my $fields = $sth->{NAME};
  $sth->finish;

  return $fields;
}

sub get_filename {
  my $table = shift;
  return "$JUICEDIR/database/data/$table.csv"
}
