#!/usr/bin/perl
# Copyright 2004 Jerzy Wachowiak

use strict;
use warnings;
use DBI;
use Getopt::Std;

# Option retrival
getopts( "msht:d:u:p:" );
our ( $opt_m, $opt_s, $opt_t );
our( $opt_d, $opt_u, $opt_p, $opt_h );
unless ( $opt_m or $opt_s or $opt_t or $opt_h or $opt_d ){ $opt_h = 1 };

if ( defined( $opt_h ) ){
    print <<EOU;

USAGE:
$0 -d database [-u user] [-p password] -t thread [-ms]

DESCRIPTION:
xdshow displays messages and statistics belonging to a thread from the database:
-m\t\tshows only messages belonging to the thread (option);
-s\t\tshows only statistic belonging to the thread (option);
-t thread\tthe message thread to act on;
-d name\t\tPostgreSQL database name;
-u user\t\tusername, if no switch, root assumed;
-p password\tpassword, if no switch, root password assumed.

EOU
    exit 0
}

unless( $opt_t ){
    print "$0: Switch -t thread is missing.\n";
    exit 1
}

# Database with most common values for root on postgresql:
my ($DBIdriver, $database, $DBIuser, $DBIpassword);
$DBIdriver = "dbi:Pg:dbname="; 
$database = $opt_d  if $opt_d;
unless( defined( $database ) ){
    print "$0: Switch -d is missing.\n";
    exit 1
}
$DBIuser = "";
$DBIuser = $opt_u  if $opt_u;
$DBIpassword = "";
$DBIpassword = $opt_p  if $opt_p;

my %attr = ( PrintError=>1, RaiseError=>1 ); 
my $dbh = DBI->connect( $DBIdriver.$database, $DBIuser, $DBIpassword, \%attr );

# Main body:
if ( !defined( $opt_m ) and  !defined( $opt_s ) ){ $opt_m =  $opt_s = 1 };
my ( $sqlcommand, $sth, @row );

# Option show statistics: 
if ( $opt_s ){
    $sqlcommand = "select * from statistics where thread = '$opt_t' ";
    $sth = $dbh->prepare( $sqlcommand );
    $sth->execute();
    while ( @row = $sth->fetchrow_array() ) { print join("; ", @row), "\n" }
}

# Option show messages
if ( $opt_m ){
    $sqlcommand = "select * from messages where thread = '$opt_t' ";
    $sth = $dbh->prepare( $sqlcommand );
    $sth->execute();
    no warnings;
    while ( @row = $sth->fetchrow_array() ) { print join("; ", @row), "\n" }
}

$dbh->disconnect();
exit 0