########################################################################
# COPYRIGHT - VIX IP PTY LTD ("VIX"). ALL RIGHTS RESERVED.
#
# Module name   : jats_extract_packages.pl
# Module type   : Makefile system
# Compiler(s)   : Perl
# Environment(s): jats build system
#
# Description   : Extracts the contents of dpkg_archive for a set of packages
#                 for a specified release.
#                 
#                 Temp utility to assist Pulse Integration developers
#......................................................................#

require 5.008_002;
use File::Basename;
use File::Copy;
use File::Path;
use strict;
use warnings;
use JatsEnv;
use JatsError;
use JatsSystem;
use JatsRmApi;
use FileUtils;
use DBI;
use Getopt::Long;
use Pod::Usage;                             # required for help support

#
#   Config Options
#
my $VERSION = "1.0.0";                      # Update this
my $opt_help = 0;
my $opt_verbose = $ENV{'GBE_VERBOSE'};      # Allow global verbose
my $opt_rtagid;
my $opt_rootdir = '.';
my $opt_test;


#
#   Constants
#
my @ignoreList = qw (android-ndk Dinkumware_STL netbula);
#
#   Globals
#
my $DM_DB;              # Data Base Interface

#-------------------------------------------------------------------------------
# Function        : Main
#
# Description     : Main entry point
#                   Parse user options
#
# Inputs          :
#
# Returns         :
#

my $result = GetOptions (
                "help:+"            => \$opt_help,              # flag, multiple use allowed
                "manual:3"          => \$opt_help,              # flag, multiple use allowed
                "verbose:+"         => \$opt_verbose,           # flag
                "rtagid|rtag_id=s"  => \$opt_rtagid,            # Number
                "rootdir=s"         => \$opt_rootdir,           # string

                "test"              => \$opt_test,              # 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_help > 2);

ErrorConfig( 'name'    => 'GenDeploy',
             'verbose' => $opt_verbose );

#
#   Sanity tests
#

# Supplied rootdir must exists as a directory
Error("Root dir not specified") 
    unless defined $opt_rootdir;
Error("Root dir not a valid directory: ", $opt_rootdir )
    unless( -d $opt_rootdir );

    # Environment var GBE_DPKG must exists as a directory
Error("GBE_DPKG Environment var is not a directory")
    unless ( -d $ENV{GBE_DPKG} );


#   Non Filter operations
#   Must supply an rtagid
Error("Need --rtagid", "Example: -rtagid=2362" )
    unless ($opt_rtagid);

#
#   This command is destined to be used in a directory where group permissions
#   are important. Ensure that the user is not killing group access
#
umask 0002;
Message("Copying packages from $ENV{GBE_DPKG} to $opt_rootdir");

#
#   Processing
#
connectRM(\$DM_DB);
GetPackageData();               # Get RM Data
exit 0;

#-------------------------------------------------------------------------------
# Function        : GetPackageData 
#
# Description     : Extract data from RM based on the provided rtag_id
#
# Inputs          : 
#
# Returns         : 
#
sub GetPackageData
{
    my $baseTar = 'stuff.tar';
    System ("tar cvf $baseTar --files-from /dev/null");


    my $m_sqlstr =  "SELECT p.PKG_NAME, pv.PKG_VERSION" .
                    " FROM package_versions pv, RELEASE_CONTENT rc, PACKAGES p" .
                    " WHERE rc.rtag_id = " . $opt_rtagid .
                    " AND rc.pv_id = pv.pv_id" .
                    " and p.PKG_ID = pv.pkg_id";

    my ( $PKG_NAME, $PKG_VERSION );
    my $sth = $DM_DB->prepare($m_sqlstr);
    if ( defined($sth) )
    {
        if ( $sth->execute( ) )
        {
            if ( $sth->rows )
            {
                while ( ( $PKG_NAME, $PKG_VERSION ) = $sth->fetchrow_array )
                {
                    my $skip = 0;
                    foreach ( @ignoreList)
                    {
                        if (uc($_) eq uc($PKG_NAME))
                        {
                            $skip = 1;
                            last;;
                        }
                    }
                    next if $skip;


                    Verbose ("Deployable: $PKG_NAME, $PKG_VERSION");
                    my $pkgDir = "$ENV{GBE_DPKG}/$PKG_NAME";
                    my $srcDir = "$ENV{GBE_DPKG}/$PKG_NAME/$PKG_VERSION";
                    my $dstDir = $opt_rootdir;

                    if ( -d "$srcDir" )
                    {
                        my $tarName = join ( '_' , $PKG_NAME , $PKG_VERSION ) . '.tar.gz';
                        Message ("Processing: $tarName");
                        System("tar --transform 's,^\\.,$PKG_NAME/$PKG_VERSION,' --exclude='./lcov' --exclude='./utfResults' -rf $baseTar -C $srcDir .");
                    }
                    elsif ( ! -d "$pkgDir" )
                    {
                        # if srcDir and pkgDir dont exist then package is not in dpkg_archive so display message
                        Warning("Skipping Package $PKG_NAME/$PKG_VERSION as it does not exist in dpkg_archive");
                    }
                    else
                    {
                        # However if srcDir does not exist but pkgDir does exist then the package version is missing which maybe an issue
                        Warning("Missing Version $PKG_VERSION for Package $PKG_NAME in dpkg_archive");
                    }
                }

                Message ("Compressing the result");
                System ("gzip $baseTar");
            }
            else
            {
                Error("No Packages for rtagid: $opt_rtagid");
            }
            $sth->finish();
        }
        else
        {
            Error("Execute failure", $sth->errstr(), $m_sqlstr );
        }
    }
    else
    {
        Error("Prepare failure", $sth->errstr(), $m_sqlstr );
    }
}

#-------------------------------------------------------------------------------
#   Documentation
#

=pod

=for htmltoc    DEPLOY::jats_extract_packages

=head1 NAME

jats_extract_packages - Generate a tarzip for all packages in a release

=head1 SYNOPSIS

  jats jats_extract_packages [options]

 Options:
    -help                   - Brief help message
    -help -help             - Detailed help message
    -man                    - Full documentation
    -rtagid=xxx             - Specify the Release Manager RtagId to process
    -rootdir=xxx            - Specifies the root of the releases directory

    -test                   - Just log actions without copying files.
    -verbose                - Enable verbose output

=head1 OPTIONS

=over 8

=item B<-help>

Print a brief help message and exits.

=item B<-help -help>

Print a detailed help message with an explanation for each option.

=item B<-man>

Prints the manual page and exits.

=item B<-rtagid=xxx>

This option specifies one or more RTAG_ID's to use as the source of packages that will be copied.
The ID will be used to get a unique list of package/versions that can be copied from dpkg_archive.

This option is Mandatory, for non-filter command.

=item B<-rootdir=xxx>

This option specifies the root directory where the packages will be copied to.

The specified directory must exist.

The default value is the current directory.

=item B<-test>

This option will display what would be copied without actually copying anything

=item B<-verbose>

This option will display progress information as the program executes.

=back

=head1 DESCRIPTION

This program is a temp kludge to keep the IT developers happy.

It will create a tar.gz file of all the packages in a specified release in a dpkg_archive structure.

=cut

