########################################################################
# COPYRIGHT - VIX IP PTY LTD ("VIX"). ALL RIGHTS RESERVED.
#
# Module name   : bcc_svnconvert.pl
# Module type   : Makefile system
# Compiler(s)   : Perl
# Environment(s): jats
#
# Description   : Determine BCC packaged that need to have their source path
#                 massaged
#
#......................................................................#

require 5.006_001;
use strict;
use warnings;
use JatsError;
use JatsSystem;
use Getopt::Long;
use Pod::Usage;                             # required for help support
use JatsRmApi;
use ConfigurationFile;

use DBI;
use HTTP::Date;

my $VERSION = "1.2.3";                      # Update this
my $opt_verbose = 0;
my $opt_help = 0;
my $opt_manual;
my $opt_rm = 'RELMANU1';
my $opt_test = 1;
my $opt_force;
my $opt_checkOperation;
my $opt_package;
my $opt_report = 0;
my $opt_live;

my $RM_DB;
my %Packages;

#-------------------------------------------------------------------------------
# Function        : Main Entry
#
# Description     :
#
# Inputs          :
#
# Returns         :
#
my $result = GetOptions (
                "help+"         => \$opt_help,          # flag, multiple use allowed
                "manual"        => \$opt_manual,        # flag
                "verbose+"      => \$opt_verbose,       # flag
                'database:s'    => \$opt_rm,
                'test!'         => \$opt_test,
                'force!'        => \$opt_force,
                'package:s'     => \$opt_package,
                'check:s'       => \$opt_checkOperation,
                'report:+'      => \$opt_report,
                'live'          => \$opt_live,
                );

#
#   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));
ErrorConfig( 'name' => 'BCC_SVNCVT' );

if ( $opt_live )
{
    $opt_rm = 'RELEASEM';
}


$ENV{GBE_RM_LOCATION} = 'jdbc:oracle:thin:@auperaprm01:1521:' . $opt_rm;
unless ( $opt_rm eq 'RELEASEM' )
{
    Warning ("Using internal user/passowrd");
    $ENV{GBE_RM_USERNAME} = 'RELEASE_MANAGER';
    $ENV{GBE_RM_PASSWORD} = 'RELEASE_MANAGER';
    $ENV{GBE_RM_LOCATION} = 'jdbc:oracle:thin:@auperaora07.vix.local:1521:' . $opt_rm;
}
else
{
    $ENV{GBE_RM_USERNAME} = 'RM_READONLY';
    $ENV{GBE_RM_PASSWORD} = 'RM_READONLY';
}

#
#   Check operation
#
if ( $opt_checkOperation )
{
    Message ("Check RM operation");
    Error ("PVID must be specified via -package option") unless $opt_package;
    intoReleaseManager ($opt_package, $opt_checkOperation);
    Message ("Check Complete OK");
    exit 0;
}


getSvnPackages();
Message ("Packages to process: " . scalar keys %Packages);
#DebugDumpData("Packages", \%Packages );
my $count = 0;
foreach my $pvid ( keys %Packages )
{
    $count++;
    my $vcstag = $Packages{$pvid}{vcstag};
    if ( $vcstag )
    {
        my $newtag = $vcstag;
        $newtag =~ s~SVN::FRBESASVN01/~SVN::FRBESASVN01/~;
        $Packages{$pvid}{newvcstag} = $newtag;
        Message ("$count, $pvid, $vcstag, $newtag" );
        intoReleaseManager($pvid, $newtag);
#last;
    }
}
outputData();

exit 0;

#-------------------------------------------------------------------------------
# Function        : getSvnPackages
#
# Description     : Determine all candiate releases
#
# Inputs          : 
#
# Returns         : 
#
sub getSvnPackages
{
    my (@row);

    # if we are not or cannot connect then return 0 as we have not found anything
    connectRM(\$RM_DB) unless $RM_DB;

    # First get all packages that are referenced in a Release
    # This will only get the top level packages
    # From non-archived releases

    my $m_sqlstr = "SELECT" .
                        " pv.PV_ID, ".                                          #[0]
                        " pkg.PKG_NAME, ".                                      #[1]
                        " pv.PKG_VERSION, ".                                    #[2]
                        " release_manager.PK_RMAPI.return_vcs_tag(pv.PV_ID) ". #[4]
                   " FROM RELEASE_MANAGER.PACKAGE_VERSIONS pv,".
                   "      RELEASE_MANAGER.PACKAGES pkg ".
                   " WHERE pv.src_path like 'FRBESA%'".
                   "   AND pv.PKG_ID = pkg.PKG_ID" ;
    my $sth = $RM_DB->prepare($m_sqlstr);
    if ( defined($sth) )
    {
        if ( $sth->execute( ) )
        {
#            print "--- Execute\n";
            if ( $sth->rows )
            {
#                print "--- Execute ROWS\n";
                while ( @row = $sth->fetchrow_array )
                {
                    print join (',',@row), "\n" if ($opt_verbose);
                    my %data;
                    $data{pvid} = $row[0];
                    $data{name} = $row[1];
                    $data{version} = $row[2];
                    $data{vcstag} = $row[3];
                    $Packages{$row[0]} = \%data;
                }
            }
#            print "--- Finish\n";
            $sth->finish();
        }
        else
        {
            Error("Execute failure: $m_sqlstr", $sth->errstr() );
        }
    }
    else
    {
        Error("Prepare failure" );
    }
}

#-------------------------------------------------------------------------------
# Function        : intoReleaseManager
#
# Description     : Update VCS tags in RM
#
# Inputs          : $pvid           - PVId
#                   $tag            - New Tag
#
# Returns         : 
#
sub intoReleaseManager
{
    my ($pvid, $new_tag ) = @_;
    my @row;
    my $user = 3768;            # buildadm

    connectRM(\$RM_DB, $opt_verbose) unless $RM_DB;

    my $m_sqlstr =  "begin release_manager.update_vcs_details($pvid, '$new_tag', $user); end;";
    my $sth = $RM_DB->prepare($m_sqlstr);
    if ( defined($sth) )
    {
        if ( $sth->execute( ) )
        {
            if ( $sth->rows )
            {
                while ( @row = $sth->fetchrow_array )
                {
                    print "Data: @row\n";
                }
            }
            $sth->finish();
        }
        else
        {
            Error("Execute failure: $m_sqlstr", $sth->errstr() );
        }
    }
    else
    {
        Error("Prepare failure" );
    }
}

#-------------------------------------------------------------------------------
# Function        : outputData
#
# Description     : Write out data in a form to allow post processing
#
# Inputs          : 
#
# Returns         : 
#
sub outputData
{
    my $file = "bcc_svnlog.txt";
    Message ("Create: $file");
    my $fh = ConfigurationFile::New( $file );

    $fh->DumpData(
        "\n# Packages.\n#\n",
        "ScmPackages", \%Packages );

    #
    #   Close out the file
    #
    $fh->Close();
}

