#!/usr/bin/env perl
#
# dsrootindex:  Extract the root data store index from the database.
# The output is in DataStore index.txt format
#

use strict;
use warnings;

use DBI;

use PS::IPP::Config qw($PS_EXIT_SUCCESS
		       $PS_EXIT_UNKNOWN_ERROR
		       $PS_EXIT_SYS_ERROR
		       $PS_EXIT_CONFIG_ERROR
		       $PS_EXIT_PROG_ERROR
		       $PS_EXIT_DATA_ERROR
		       $PS_EXIT_TIMEOUT_ERROR
		       metadataLookupStr
		       metadataLookupBool
		       caturi
		       );

my $dbh = getDBHandle();

my $stmt = $dbh->prepare("SELECT * FROM dsProduct");
$stmt->execute();

print "# productID  |Most recent |Time registered     |type     |Description                     |\n";

while( my $row = $stmt->fetchrow_hashref()) {
    my $prod_id = $row->{prod_id};

    my ($date, $time) = split / /, $row->{last_update};
    my $datetime = $date . "T" . $time . "Z";

    my $last_fs =  $row->{last_fs};
    if (!$last_fs) {
        # dsrootls is fussy when this field is blank
        $last_fs = "none";
    }

    my $line = sprintf "%-13s|%-12s|%-20s|%-9s|%-32s|\n",  $row->{prod_name}, $last_fs, $datetime,
        $row->{type}, $row->{description};

    print $line;
}

# todo move to a module
sub getDBHandle {
    my $ipprc =  PS::IPP::Config->new(); # IPP Configuration
    my $siteConfig = $ipprc->{_siteConfig};

    my $dbserver = metadataLookupStr($siteConfig, 'DBSERVER');
    my $dbname   = metadataLookupStr($siteConfig, 'DBNAME');
    my $dbuser   = metadataLookupStr($siteConfig, 'DBUSER');
    my $dbpass   = metadataLookupStr($siteConfig, 'DBPASSWORD');
    exit ($PS_EXIT_CONFIG_ERROR) unless defined $dbserver and $dbname and $dbuser and $dbpass;

    my $dsn = "DBI:mysql:host=$dbserver;database=$dbname";

    my $dbh = DBI->connect($dsn, $dbuser, $dbpass) or die "Cannot connect to server\n";
    return $dbh;
}
