#! perl
########################################################################
# COPYRIGHT - VIX IP PTY LTD ("VIX"). ALL RIGHTS RESERVED.
#
# Module name   : jats.sh
# Module type   : Makefile system
# Compiler(s)   : n/a
# Environment(s): jats
#
# Description   : Get package information
#                 for a package name and version as specified on the
#                 command line.
#
#                 Walks backwards and locates the previous version of the
#                 package. The is repeated.
#
# Usage:
#
# Version   Who      Date        Description
#
#......................................................................#

require 5.006_001;
use strict;
use warnings;
use JatsError;
use JatsRmApi;


#use Data::Dumper;
use Cwd;
use DBI;
use Getopt::Long;
use Pod::Usage;                             # required for help support

my $GBE_PERL     = $ENV{'GBE_PERL'};        # Essential ENV variables
my $GBE_CORE     = $ENV{'GBE_CORE'};
my $RM_DB;

################################################################################
#   Global data
#
my $VERSION = "1.0.0";
my %ReleasePackages;            # Packages in the release
my %BuildPackages;              # Packages for this build
my $base_name;
my $base_version;
my $last_pv_id;


#
#   Options
#
my $opt_help = 0;
my $opt_manual = 0;
my $opt_verbose = 0;

my $result = GetOptions (
                "help+"     => \$opt_help,          # flag, multiple use allowed
                "manual"    => \$opt_manual,        # flag
                "verbose+"  => \$opt_verbose,       # flag
                );

#
#   Process help and manual options
#
pod2usage(-verbose => 0, -message => "Version: $VERSION")  if ($opt_help == 1  || ! $result);
pod2usage(-verbose => 1)  if ($opt_help == 2 );
pod2usage(-verbose => 2)  if ($opt_manual || ($opt_help > 2));

#
#   Configure the error reporting process now that we have the user options
#
ErrorConfig( 'name'    =>'PLAY9',
             'verbose' => $opt_verbose );

unless ( $ARGV[0] && $ARGV[1] )
{
    Error( "Specify a package as 'name' 'version'" );
}
$base_name = $ARGV[0];
$base_version = $ARGV[1];
Verbose( "Base Package: $base_name, $base_version");

#
#   Body of the process
#
GetData ( $base_name, $base_version );

my %seen_pvid;

while ( ! exists ($seen_pvid{$last_pv_id } ))
{
    $seen_pvid{$last_pv_id} = 1;
    GetData_bypvid( $last_pv_id );
}

exit 0;


#-------------------------------------------------------------------------------
# Function        : GetData
#
# Description     :
#
# Inputs          : pkg_name
#                   pkg_ver
#
# Returns         :
#
sub GetData
{
    my ( $pkg_name, $pkg_ver ) = @_;
    my (@row);
    my $pv_id;

    #
    #   Establish a connection to Release Manager
    #
    connectRM(\$RM_DB) unless ( $RM_DB );

    #
    #   Extract data from Release Manager
    #
    my $m_sqlstr = "SELECT pkg.PKG_NAME, pkg.PKG_ID, pv.PKG_VERSION, pv.PV_ID, pv.SRC_PATH, pbi.BSA_ID, pv.LAST_PV_ID" .
                   " FROM PACKAGES pkg, PACKAGE_VERSIONS pv, PACKAGE_BUILD_INFO pbi" .
                   " WHERE pkg.PKG_NAME = \'$pkg_name\' AND pkg.PKG_ID = pv.PKG_ID AND pv.PKG_VERSION = \'$pkg_ver\' AND pv.PV_ID = pbi.PV_ID";
                   
    my $sth = $RM_DB->prepare($m_sqlstr);
    if ( defined($sth) )
    {
        if ( $sth->execute( ) )
        {
            if ( $sth->rows )
            {
                while ( @row = $sth->fetchrow_array )
                {
                    Verbose( "DATA: " . join(',', @row) );
                    my $path = $row[4] || 'None Specified';
                    my $be = $row[5] || 'Unknown';
                    $last_pv_id = $row[6] || 'Unknown';
                    print "$pkg_name, $pkg_ver, $path, $be, $last_pv_id\n";
                    last;
                }
            }
            $sth->finish();
        }
    }
    else
    {
        Error("GetData:Prepare failure" );
    }
}

#-------------------------------------------------------------------------------
# Function        : GetData_bypvid
#
# Description     :
#
# Inputs          : pv_id
#
# Returns         :
#
sub GetData_bypvid
{
    my ( $pv_id ) = @_;
    my (@row);

    #
    #   Establish a connection to Release Manager
    #
    connectRM(\$RM_DB) unless ( $RM_DB );

    #
    #   Extract data from Release Manager
    #
    my $m_sqlstr = "SELECT pkg.PKG_NAME, pv.PKG_VERSION, pkg.PKG_ID, pv.PV_ID, pv.LAST_PV_ID".
                   " FROM PACKAGES pkg, PACKAGE_VERSIONS pv" .
                   " WHERE pv.PV_ID = \'$pv_id\' AND pkg.PKG_ID = pv.PKG_ID";
                   
                   
    my $sth = $RM_DB->prepare($m_sqlstr);
    if ( defined($sth) )
    {
        if ( $sth->execute( ) )
        {
            if ( $sth->rows )
            {
                while ( @row = $sth->fetchrow_array )
                {
                    Verbose( "DATA: " . join(',', @row) );
                    my $pkg_name = $row[0] || 'Unknown';
                    my $pkg_ver = $row[1] || 'Unknown';
                    $last_pv_id = $row[4] || 'Unknown';
                    print "$pkg_name, $pkg_ver, $last_pv_id\n";
                    last;
                }
            }
            $sth->finish();
        }
    }
    else
    {
        Error("GetData:Prepare failure" );
    }
}
