#!/usr/bin/perl

# report_export - Created by James Pattie, PC & Web Xperience, Inc.
# 09/29/2000.  This script will export the system level reports into a text
# file for inclusion in the distribution.

use strict;
use Pg;

use vars '$conn';
use vars '$result';

my $version = "";
my $db_name = "";
my $db_passwd = "";
my $db_host = "";
my $db_user = "";

if (length $db_name <= 0)
{
  print "Database Name:";
  while (length $db_name <= 0)
  {
    $db_name = <STDIN>;
  }
  chomp $db_name;
  print "Database Host(Server) [localhost]:";
  $db_host = <STDIN>;
  chomp $db_host;
  if ($db_host == "")
  {
    $db_host = "localhost";
  }
  
  print "Database User [portal]:";
  $db_user = <STDIN>;
  chomp $db_user;
  if ($db_user == "")
  {
    $db_user = "portal";
  }
  print "    The data you entered was:\n$db_name\n";
  print "$db_host\n$db_user\n";
  print "\nType Ctrl+C to cancel or Enter to continue:\n";
  <STDIN>;
}

# now call pg_dump on these tables and then massage the resulting data files.
print("Dumping report_type_tb\n");
my $error = `/usr/bin/pg_dump -U$db_user -a -d -D -h $db_host -t report_type_tb $db_name`;
if ($error =~ /([E|e]rror|incorrect password)/)
{
  die "Error:  Failed to dump report_type_tb!\n$error\n";
}
if (length $error == 0)
{
  die "Error:  Failed to dump report_type_tb!\n$error\n";
}

my @reports = split /\n/, $error;

print("Dumping report_data_tb\n");
my $error = `/usr/bin/pg_dump -U$db_user -a -d -D -h $db_host -t report_data_tb $db_name`;
if ($error =~ /([E|e]rror|incorrect password)/)
{
  die "Error:  Failed to dump report_data_tb!\n$error\n";
}
if (length $error == 0)
{
  die "Error:  Failed to dump report_data_tb!\n$error\n";
}

my @report_data = split /\n/, $error;

# Open the file system_reports.psql and work with it.
open(SYSREPORTS, ">system_reports.psql") or die "Error: Opening Reports File Failed!\n$!\n";

my $skip;
my $added;
foreach my $line (@reports)
{ 
#  print $line."\n";
  if ($line =~ /^INSERT INTO "?report_type_tb"?/)
  {
    my @line = split ("VALUES", $line);
    @line = split (",", $line[1]);
#    print $line[1];
    my $id = $line[1];
    if ($id < 500)
    {
      print SYSREPORTS $line . "\n";
      $added .= "$id,";
    }
    else
    { 
      $skip .= "$id,";
    }
  }
}
print "Skipped: $skip\n";
print "Added: $added\n";
$skip = "";
$added = "";
print "\n\nNow processing data\n";
#print "Press enter to continue";
#<STDIN>;
foreach my $line (@report_data)
{
  if ($line =~ /^INSERT INTO "?report_data_tb"?/)
  {
    my @line = split ("VALUES", $line);
    $line[1] =~ s/^ \(//;
    $line[1] =~ s/\);$//; 
    @line = split (",", $line[1]);
    my $id = $line[0];
    if ($id < 500)
    {
      print SYSREPORTS $line . "\n";
      $added .= "$id,";
    }
    else
    { 
      $skip .= "$id,";
    }
  }
}
print "Skipped: $skip\n";
print "Added: $added\n";

close (SYSREPORTS);

print "\nReport Exportation Succeeded.\n";
